I want to obtain the module from which a Python object is from. Both
x.__module__
and
x.__class__.__module__
seem to work. Are these completely redundant? Is there any reason to prefer one over another?
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.
A module can find out its own module name by looking at the predefined global variable __name__.
Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance. Use the type() function and __name__ to get the type or class of the Object/Instance.
If x
is a class then x.__module__
and x.__class__.__module__
will give you different things:
# (Python 3 sample; use 'class Example(object): pass' for Python 2)
>>> class Example: pass
>>> Example.__module__
'__main__'
>>> Example.__class__.__module__
'builtins'
For an instance which doesn't define __module__
directly the attribute from the class is used instead.
>>> Example().__module__
'__main__'
I think you need to be clear what module you actually want to know about. If it is the module containing the class definition then it is best to be explicit about that, so I would use x.__class__.__module__
. Instances don't generally record the module where they were created so x.__module__
may be misleading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With