Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 prefer one over another?

like image 851
Joonas Pulakka Avatar asked Mar 11 '11 09:03

Joonas Pulakka


People also ask

What is __ class __ in Python?

__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 .

What is __ module __ Python?

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.

How do I print a Python module name?

A module can find out its own module name by looking at the predefined global variable __name__.

How do I get the class name of an object in Python?

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.


1 Answers

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.

like image 193
Duncan Avatar answered Sep 18 '22 01:09

Duncan