I have the following in Python 2.7:
class MyClass(object):
...
@property
def my_attr(self):
...
@my_attr.setter
def my_attr(self, value):
...
I use getter/setter so that I can do some logic in there.
Then I can call:
import myModule
test = myModule.MyClass()
test.my_attr = 9
I would like to use an alias at the module level so that I can do something like that:
import myModule
myModule.my_attr = 9
Is there a way to do that?
Yes, absolutely; the key is that modules are themselves objects. First you need to make MyClass subclass the module type:
from types import ModuleType
class MyClass(ModuleType):
...
Then you replace the current module with an instance of MyClass:
import sys
sys.modules[__name__] = MyClass(__name__)
Note that this can be pretty confusing to static analysers and to people reading your code.
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