Python Glossary Русский

Python 3.7+typesterm

types.MethodDescriptorType

descriptors and C wrappers

The type of a regular built-in class method taken from the class: str.join, list.append. Called through the class, its first argument is the instance.

Syntax

isinstance(obj, types.MethodDescriptorType)

str.join is a MethodDescriptorType, while ', '.join is already a BuiltinFunctionType (a bound C method). That enables a handy trick: str.upper can be passed to map as a one-argument function — map(str.upper, words). It only works for strings, though: str.upper(5) raises TypeError, because the descriptor checks the type of self, unlike functions written in Python.

Examples

import types
print(isinstance(str.upper, types.MethodDescriptorType))  # → True
print(isinstance('a'.upper, types.BuiltinFunctionType))  # → True
print(list(map(str.upper, ['ok', 'go'])))  # → ['OK', 'GO']
try:
    str.upper(5)
except TypeError:
    print('TypeError')  # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy