7

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?

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
  • 1
    [This answer](https://stackoverflow.com/a/31148962/3644818) explain how the object `__module__` is created from the class `__module__`. – F.Raab Mar 20 '20 at 13:43

1 Answers1

14

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.

efotinis
  • 14,565
  • 6
  • 31
  • 36
Duncan
  • 92,073
  • 11
  • 122
  • 156