Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use alias for a property in Python at module level

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?

like image 744
MasterMind Avatar asked Nov 03 '25 12:11

MasterMind


1 Answers

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.

like image 96
ecatmur Avatar answered Nov 06 '25 03:11

ecatmur