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

Posted on

Question :

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

Can anybody explain to me with adequate examples whats the difference b/w

>>> import inspect
>>> inspect.getmembers(1)


>>> type(1).__dict__.items()


>>> dir(1)  

except that they show an decreasing no.s of attributes & methods in that order.
1 is integer (but it can be of any type.)


>>>obj.__class__.__name__  #gives the class name of object  
>>>dir(obj)                #gives attributes & methods  
>>>dir()                   #gives current scope/namespace
>>>obj.__dict__            #gives attributes
Asked By: Jibin


Answer #1:

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.

Answered By: Jibin

Leave a Reply

Your email address will not be published. Required fields are marked *