10000 [doc] bpo-45680: Disambiguate ``__getitem__`` and ``__class_getitem__`` in the data model. by AlexWaygood · Pull Request #29389 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[doc] bpo-45680: Disambiguate __getitem__ and __class_getitem__ in the data model. #29389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Nov 18, 2021
Prev Previous commit
Next Next commit
Improve code snippet
  • Loading branch information
AlexWaygood authored Nov 8, 2021
commit c1955d7faf533388d45718dab6e0b8d3d3922784
8 changes: 6 additions & 2 deletions Doc/reference/datamodel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2282,17 +2282,21 @@ follows something like the following process to decide whether
:meth:`~object.__getitem__` or :meth:`~object.__class_getitem__` should be
called::

from inspect import isclass

def subscribe(obj, x):
"""Return the result of the expression `obj[x]`"""

class_of_obj = type(obj)

# If the class of `obj` defines `__getitem__()`,
# call `type(obj).__getitem__()`
if hasattr(class_of_obj, '__getitem__'):
return class_of_obj.__getitem__(obj, x)

# Else, if `obj` defines `__class_getitem__()`,
# Else, if `obj` is a class and defines `__class_getitem__()`,
# call `obj.__class_getitem__()`
elif hasattr(obj, '__class_getitem__'):
elif isclass(obj) and hasattr(obj, '__class_getitem__'):
return obj.__class_getitem__(x)

# Else, raise an exception
Expand Down
0