Reputation: 1855
I have an instance of a class SomeClass
that is defined within a module m
. For the behavior of SomeClass
, I need to access the following list:
m.__all__
How can I access this list from an instance of SomeClass
?
Instances of SomeClass
have the following built-in:
SomeClass.__module__
However, this is simply a string. How can I access the module itself, and its attributes?
Upvotes: 3
Views: 330
Reputation: 59178
The sys
module contains a dictionary modules
which maps the names of loaded modules to the modules themselves. Together with SomeClass.__module__
, you can use this to access the module SomeClass
was imported from.
For instance, with a module m.py
like this:
# m.py
__all__ = [
"A_CONSTANT",
"SomeClass",
]
A_CONSTANT = "foo"
class SomeClass: pass
... the following works:
>>> from m import SomeClass
>>> SomeClass.__module__
'm'
>>> import sys
>>> sys.modules[SomeClass.__module__]
<module 'm' from '/path/to/m.py'>
>>> sys.modules[SomeClass.__module__].__all__
['SomeClass', 'A_CONSTANT']
>>> sys.modules[SomeClass.__module__].A_CONSTANT
'foo'
Upvotes: 4