Getting the module name: x .__ module__ vs x .__ class __.__ module__

I want to get the module from which the Python object comes from. Both

x.__module__ 

and

 x.__class__.__module__ 

seems to work. Are they completely redundant? Is there any reason to prefer one over the other?

+4
python module python-module
Mar 11 2018-11-11T00:
source share
1 answer

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 that does not directly define __module__ , an attribute from the class is used instead.

 >>> Example().__module__ '__main__' 

I think you need to clearly understand on which module you really want to find out. If this is a module containing a class definition, then it is best to be explicit in this question, so I would use the x.__class__.__module__ . Instances usually do not write the module in which they were created, so x.__module__ can be misleading.

+11
Mar 11 2018-11-11T00:
source share
β€” -



All Articles