inspect.getmembers() vs __dict__.items() vs dir()

dir() allows you to customize what attributes your object reports, by defining __dir__().

From the manual, if __dir__() is not defined:

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

This is also what inspect.getmembers() returns, except it returns tuples of (name, attribute) instead of just the names.

object.__dict__ is a dictionary of the form {key: attribute, key2: atrribute2} etc.

object.__dict__.keys() has what the other two are lacking.

From the docs on inspect.getmembers():

getmembers() does not return metaclass attributes when the argument is a class (this behavior is inherited from the dir() function).

For int.__dict__.keys(), this is

['__setattr__', '__reduce_ex__', '__reduce__', '__class__', '__delattr__', '__subclasshook__', '__sizeof__', '__init__']

To summarize, dir() and inspect.getmembers() are basically the same, while __dict__ is the complete namespace including metaclass attributes.

Leave a Comment