Login
You're viewing the aleph.land public feed.
  • Oct 3, 2026, 11:47 PM

    Python Tip #276 (of 365):

    Make self positional-only when accepting "**kwargs".

    This class accepts arbitrary keyword arguments... except for self:

    >>> class Namespace:
    ... def __init__(self, **kwargs):
    ... for name, value in kwargs.items():
    ... setattr(self, name, value)
    ...
    >>> space = Namespace(other=2, self=1)
    Traceback (most recent call last):
    ...
    TypeError: Namespace.__init__() got multiple values for argument 'self'

    🧵 (1/3)

    #Python #DailyPythonTip

    💬 1🔄 2⭐ 1

Replies

  • Oct 3, 2026, 11:47 PM

    Python got multiple values for self because the self argument is ALWAYS specified for every method.

    But we were trying to ADDITIONALLY specify self for capturing in our kwargs dictionary.

    We can fix this by putting a / between self and "**kwargs", forcing self to be positional-only:

    def __init__(self, /, **kwargs):

    Now a self keyword argument is captured into our kwargs dictionary instead:

    >>> space = Namespace(other=2, self=1)
    >>> space.self
    1

    🧵 (2/3)

    💬 1🔄 0⭐ 0
  • Oct 3, 2026, 11:47 PM

    Specifying positional-only arguments is rare. But a method that accepts arbitrary keyword arguments is one of the few cases when it's particularly helpful.

    🧵 (3/3)

    💬 1🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • Oct 4, 2026, 1:37 AM

    @treyhunner this is part of a general genre of "completeness strategy" tips that I think are particularly challenging in Python. we have a lot of common idioms in the community that randomly create dark little corners like "you can't use an underscore here" or "this creates 3 additional reserved names, implicitly" or "now super() doesn't work but only in diamond inheritance" or whatever, and being aware of those edges is very important

    💬 1🔄 0⭐ 0
  • Oct 4, 2026, 2:17 AM

    @glyph There are definitely some sharp corners hiding in weird places...

    The ones that come to mind for me are different than the ones you mentioned. I'm actually not sure I know all of the examples you mentioned. 🤔

    💬 1🔄 0⭐ 0
  • Oct 4, 2026, 2:18 AM

    @treyhunner They may not all be real :). But pretty much all interactions between __init__() and super() are still full of painful awkward corners

    💬 0🔄 0⭐ 0