Skip to content

Inaccurate emulation of _PyType_Lookup() in the Descriptor HOWTO #95822

Closed
@iyume

Description

@iyume

Documentation

Doc link: https://docs.python.org/3.10/howto/descriptor.html#invocation-from-an-instance

Source: https://github.com/python/cpython/blame/eb81c1aea16914347919745e843c982ed831a9fb/Doc/howto/descriptor.rst#L585-L601

The code example is bad at https://github.com/python/cpython/blame/eb81c1aea16914347919745e843c982ed831a9fb/Doc/howto/descriptor.rst#L589

getattr(objtype, name) will go through descriptor.__get__.

Code Snippet:

class A:
    def __get__(self, obj, objtype):
        return obj, objtype

class B:
    a = A()

print(B().a)
# (<__main__.B object at 0x7ff56d0915e0>, <class '__main__.B'>)
print(B.a)  # same as getattr
# (None, <class '__main__.B'>)

Solution

Using __dict__ (or vars) instead of getattr:

print(vars(B)['a'])
# <__main__.A object at 0x7ff56cfef2b0>

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions