Richard Neumann <[email protected]> added the comment:
Thank you all for your input.
I had a look at aforementioned discussion and learned something new.
So I tried to implement the dict data model by implementing keys() and
__getitem__() accordingly:
from typing import NamedTuple
class Spamm(NamedTuple):
foo: int
bar: str
def __getitem__(self, item):
if isinstance(item, str):
try:
return getattr(self, item)
except AttributeError:
raise KeyError(item) from None
return super().__getitem__(item)
def keys(self):
yield 'foo'
yield 'bar'
def main():
spamm = Spamm(12, 'hello')
print(spamm.__getitem__)
print(spamm.__getitem__(1))
d = dict(spamm)
if __name__ == '__main__':
main()
Unfortunately this will result in an error:
Traceback (most recent call last):
File "/home/neumann/test.py", line 4, in <module>
class Spamm(NamedTuple):
RuntimeError: __class__ not set defining 'Spamm' as <class '__main__.Spamm'>.
Was __classcell__ propagated to type.__new__?
Which seems to be caused by the __getitem__ implementation.
I found a corresponding issue here: https://bugs.python.org/issue41629
Can I assume, that this is a pending bug and thusly I cannot implement the
desired behaviour until a fix?
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue42765>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com