Skip to content
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