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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With