Skip to content

NamedTuple doesn’t support overriding __new__ #526

@flying-sheep

Description

@flying-sheep

I expected the following to work like with collections.namedtuple, but it doesn’t:

_FooBase = NamedTuple('_FooBase', [('a', FrozenSet[str])])

class Foo(_FooBase):
    def __init__(self, a: Iterable[str]):
        super().__init__(frozenset(a))

but I get:

In [3]: Foo(['x'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-a93a09ef10e2> in <module>()
----> 1 Foo(['x'])

<ipython-input-8-cbd998f4721b> in __init__(self, a)
      3 class Foo(_FooBase):
      4     def __init__(self, a: Iterable[str]):
----> 5         super().__init__(frozenset(a))
      6 

TypeError: object.__init__() takes no parameters

With the 3.6 syntax, there’s an earlier error:

In [2]: class foo(NamedTuple):
   ...:     a: FrozenSet[str]
   ...:     def __init__(self, a: Iterable[str]):
   ...:         super().__init__(frozenset(a))
   ...:         
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-c99525ef7a4f> in <module>()
----> 1 class foo(NamedTuple):
      2     a: FrozenSet[str]
      3     def __init__(self, a: Iterable[str]):
      4         super().__init__(frozenset(a))
      5 

/usr/lib/python3.6/typing.py in __new__(cls, typename, bases, ns)
   2152         for key in ns:
   2153             if key in _prohibited:
-> 2154                 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
   2155             elif key not in _special and key not in nm_tpl._fields:
   2156                 setattr(nm_tpl, key, ns[key])

AttributeError: Cannot overwrite NamedTuple attribute __init__

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions