Reputation: 3155
When I define a class
class X:
pass
I can then easily see the module name where the class is defined by doing X.__module__
.
When I want to do the same for a variable
a = 5
a.__module__
I get an AttributeError: 'int' object has no attribute '__module__'
.
Is there any way how I can get the module name where a variable is defined?
Upvotes: 1
Views: 103
Reputation: 3814
This is not possible because variables in Python are not separate objects. If you write a=5;a.__module__
, that is treated exactly identically to (5).__module__
, and that doesn't make any sense since you probably have multiple variables pointing to the integer 5
.
This isn't really possible for classes either, for the same reason: X.__module__
actually returns the module in which the class was created, even if you create another variable referring to the class in a different module.
There are certain exotic situations in which this can in theory work, such as defining a class with a metaclass with a custom __prepare__
method, or if the code is being exec
ed with a custom locals
object, but those are very unusual and outside the scope of this answer.
Upvotes: 3