Accessing the __all__ list of the parent module of the class instance
I have an instance of a class SomeClass
that is defined in a module m
. For the behavior, SomeClass
I need to access the following list:
m.__all__
How can I access this list from an instance SomeClass
?
Instances SomeClass
have the following built-in interface:
SomeClass.__module__
However, this is just a string. How can I access the module itself and its attributes?
source to share
The module sys
contains a dictionary modules
that maps the names of the loaded modules to the modules themselves. Together with SomeClass.__module__
you can use this to access the module from which it SomeClass
was imported.
For example, 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'
source to share