Obtaining Module Name: X.__module__ Vs X.__class__.__module__
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
Solution 1:
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.
Post a Comment for "Obtaining Module Name: X.__module__ Vs X.__class__.__module__"