This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author conqp
Recipients bob.ippolito, conqp, eric.smith, rhettinger, steven.daprano
Date 2021-01-06.10:53:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1609930390.5.0.321275372635.issue42765@roundup.psfhosted.org>
In-reply-to
Content
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?
History
Date User Action Args
2021-01-06 10:53:10conqpsetrecipients: + conqp, rhettinger, bob.ippolito, eric.smith, steven.daprano
2021-01-06 10:53:10conqpsetmessageid: <1609930390.5.0.321275372635.issue42765@roundup.psfhosted.org>
2021-01-06 10:53:10conqplinkissue42765 messages
2021-01-06 10:53:10conqpcreate