Python Glossary Русский

all Python 3inspectfunction

inspect.getmembers()

members and modules

All attributes of an object as a list of (name, value) pairs sorted by name; a predicate keeps only the matching ones.

Syntax

inspect.getmembers(object, predicate=None) -> list[tuple[str, object]]

getmembers() reads every attribute through getattr, so it runs properties and __getattr__: a property that queries a database will execute, and any exception from it other than AttributeError aborts the whole walk. To list members without running the object's code there is getmembers_static (3.11+). The predicate receives the value, not the name: getmembers(mod, inspect.isfunction). Metaclass attributes are missing from a class's result even though hasattr sees them. The undocumented classify_class_attrs (with its Attribute tuple) sorts class attributes by kind for pydoc.

Examples

import inspect
class User:
    def __init__(self):
        self.name = 'Ann'
    @property
    def slow(self):
        print('запрос к базе')
        return 42
names = [n for n, v in inspect.getmembers(User()) if not n.startswith('_')]
print(names)  # → ['name', 'slow'] — перед этим напечатано «запрос к базе»
import inspect, math
funcs = inspect.getmembers(math, inspect.isbuiltin)
print([name for name, _ in funcs][:3])  # → ['acos', 'acosh', 'asin']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy