5

I am confused as to where __name__ is stored within a Python object.

For example, take Python str:

In [1]: hasattr(str, "__name__")
Out[1]: True

In [2]: getattr(str, "__name__")
Out[2]: 'str'

In [3]: "__name__" in str.__dict__
Out[3]: False

In [4]: "__name__" in list(dir(str))
Out[4]: False

You can see from [1] + [2] that str.__name__, that it has the value "str". However, I can't find where it's stored by using dir() and __dict__.

I know I am missing something, but from all my reading I can't figure it out. Can you please help me?

Places Looked

From these questions:

  1. python __getattr__ and __name__
  2. Why do python instances have no __name__ attribute?
    • Thank you to everyone for pointing #2 out
In [5]: str.__class__.__name__
Out[5]: 'type'

In [6]: "hi".__class__.__name__
Out[6]: 'str'

One can see a str instance has __name__ = "str" stored within __class__.

Where is __name__ = "str" within the class str?

Thanks in advance for the help!

Later Edit

Turns out this was a duplicate. The answer (as stated in the comments) is:

In [1]: type.__dict__['__name__'].__get__(str)
Out[1]: 'str'

And the reasoning can be found in these questions:

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • Hello everyone, thank you for linking the very useful question! However, the marked duplicate does not answer my question, which is where in `str` class is `"str"` being returned from when one says `str.__name__`? – Intrastellar Explorer Oct 15 '19 at 18:46
  • 2
    O.P: the result "str" is resolved via the metaclass + descriptor protocol. Try `type.__dict__['__name__'].__get__(str)`. – wim Oct 15 '19 at 18:59
  • Okay thank you everyone, I am surprised those questions/answers didn't come up in my searching. Thank you @wim for posting a TL;DR answer, and I added links to other useful questions. – Intrastellar Explorer Oct 15 '19 at 19:11

0 Answers0