You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
NamedTuple doesn’t support overriding __new__ #526
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)
3classFoo(_FooBase):
4def__init__(self, a: Iterable[str]):
----> 5 super().__init__(frozenset(a))
6TypeError: 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]
3def__init__(self, a: Iterable[str]):
4super().__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__
Reacted by Peter O'Connor, Alexey Strokach, golf-player, Ryan Williams, Joshua Bronson, lemon24, Kyra, Kevin Keating, Michał Jabłoński, EZinman and 6 more
This is by design. Note, tuple is immutable, and therefore one cannot call __init__ on it, everything is done by __new__. Also there are some other tricks to make named tuples compact and fast, so that it is prohibited to override few special methods and attributes.
Named tuples are intended to be minimalistic, for everything more complex you can use dataclasses.
oh, makes sense. then let’s make sure overriding __new__ works
I don't think it is possible either (at least it is not easy for sure). And from the example you provided it looks like you should really use something like dataclasses or attrs classes (the latter even have special support for converters).
the example is of course just an example. luckily you don’t have to guess what i want, as i can tell you exactly 😉 i want a data container that:
is typed
is immutable
has its items accessible by attribute access syntax
has a custom constructor so that i can use defaults and coercion
NamedTuple has all that but the last one, which is prevented by its current implementation. so let’s fix that implementation!
I believe this is intentional so that people don't break classes that inherit from NamedTuple.
ah, so there’s magic in play that makes __new__ behave differently from normal. OK, then let’s just fix this (maybe in the metaclass?). the fact that it doesn’t work now is an understandable hack to protect people from confusion the current implementation would otherwise cause. but it is also surprising (hence this issue being filed), and python should be predictable.
i can override __repr__ and everything, so why not wrap the constructor?
Reacted by Wei Ma, Mikhail Katliar, Paul Eipper, Alex Romanczuk, Malcolm Greaves, Grégoire Geis, Peter O'Connor, Alexey Strokach, Brian Duncan, Kevin Keating and 25 more
Agreed, this would be very useful - it's really the only think standing in the way of being able to nicely write immutable classes (well, that and the strange behaviour of inheritance)
@altaurog, the point is to subclass and override typing.NamedTuple, to get the typing benefits. That is currently not supported. Of course you can use collections.namedtuple if you don't care about typing.
But this will not work. I know people like named tuples, but TBH I think this is at a boundary of abusing them, people should use dataclasses for complex cases (they can be also made immutable), while named tuples should be reserved for simpler scenarios. The problem is that named tuples are highly optimized, and it is impossible to implement the above functionality without breaking at least some of the optimizations.
Btw there also will be (or maybe already is) a backport of dataclasses on PyPI for older Python 3.6.
My use-case is to add some assertions in __new__ to check parameter validity. Therefore it would be great to be able to overwrite __new__. It seems to be possible in a subsubclass of NamedTuple, but having the new syntax it would be more natural in the subclass.
Reacted by lemon24, Kyra, Kevin Keating, Joseph Lisee, Buck Evan, Ian Hinsdale, Michał Nazarewicz, Evan, golmschenk, Serhii Hulko and 9 more
Although a factory method would work as an alternative to overriding __new__ to some extent, it is bugprone that the normal construct (not forbidden and one may mistakenly use it) may lead to an unexpected result. For example:
As this is about enhancing the runtime behavior of a class from typing and typing is now part of Python, I am going to close this here. Please refile at bugs.python.org if still applicable.
Activity
ilevkivskyi commentedon Jan 12, 2018
This is by design. Note,
tupleis immutable, and therefore one cannot call__init__on it, everything is done by__new__. Also there are some other tricks to make named tuples compact and fast, so that it is prohibited to override few special methods and attributes.Named tuples are intended to be minimalistic, for everything more complex you can use dataclasses.
flying-sheep commentedon Jan 13, 2018
oh, makes sense. then let’s make sure overriding
__new__works:[-]NamedTuple doesn’t support overriding __init__[/-][+]NamedTuple doesn’t support overriding __new__[/+]emmatyping commentedon Jan 13, 2018
I believe this is intentional so that people don't break classes that inherit from NamedTuple.
ilevkivskyi commentedon Jan 13, 2018
I don't think it is possible either (at least it is not easy for sure). And from the example you provided it looks like you should really use something like dataclasses or
attrsclasses (the latter even have special support for converters).flying-sheep commentedon Jan 13, 2018
the example is of course just an example. luckily you don’t have to guess what i want, as i can tell you exactly 😉 i want a data container that:
NamedTuplehas all that but the last one, which is prevented by its current implementation. so let’s fix that implementation!ah, so there’s magic in play that makes
__new__behave differently from normal. OK, then let’s just fix this (maybe in the metaclass?). the fact that it doesn’t work now is an understandable hack to protect people from confusion the current implementation would otherwise cause. but it is also surprising (hence this issue being filed), and python should be predictable.i can override
__repr__and everything, so why not wrap the constructor?petered commentedon Jun 20, 2018
Agreed, this would be very useful - it's really the only think standing in the way of being able to nicely write immutable classes (well, that and the strange behaviour of inheritance)
altaurog commentedon Jun 21, 2018
I am not sure what it means to subclass
NamedTuple. How about the following?emmatyping commentedon Jun 21, 2018
@altaurog, the point is to subclass and override
typing.NamedTuple, to get the typing benefits. That is currently not supported. Of course you can usecollections.namedtupleif you don't care about typing.ilevkivskyi commentedon Jun 21, 2018
Some people ask about
But this will not work. I know people like named tuples, but TBH I think this is at a boundary of abusing them, people should use dataclasses for complex cases (they can be also made immutable), while named tuples should be reserved for simpler scenarios. The problem is that named tuples are highly optimized, and it is impossible to implement the above functionality without breaking at least some of the optimizations.
Btw there also will be (or maybe already is) a backport of
dataclasseson PyPI for older Python 3.6.petered commentedon Jun 21, 2018
There appears to be: https://github.com/ericvsmith/dataclasses
jstriebel commentedon Feb 11, 2019
My use-case is to add some assertions in
__new__to check parameter validity. Therefore it would be great to be able to overwrite__new__. It seems to be possible in a subsubclass ofNamedTuple, but having the new syntax it would be more natural in the subclass.kalessin commentedon Aug 20, 2019
You may implement a factory method instead:
tueda commentedon Sep 10, 2019
Although a factory method would work as an alternative to overriding
__new__to some extent, it is bugprone that the normal construct (not forbidden and one may mistakenly use it) may lead to an unexpected result. For example:Use dataclasses instead of enriched namedtuple in requires_provides
heyakyra commentedon Jul 29, 2020
Does this work?
remi-cab commentedon Jun 7, 2021
Someone made this really usefull NamedTuple derived MetaClass supporting inheritance :
http://zecong.hu/2019/08/10/inheritance-for-namedtuples/#instance-class-and-metaclass
source code :
https://gist.github.com/huzecong/df51502a8a6ec0bcc0e605a2ce109008
srittau commentedon Nov 4, 2021
As this is about enhancing the runtime behavior of a class from
typingandtypingis now part of Python, I am going to close this here. Please refile at bugs.python.org if still applicable.jpsnyder commentedon Jul 15, 2024
If you would like to keep the class typing style, you can do this monstrosity.