I am not even sure, whether the following is possible. My question is easily described with the following code.
My module is defined as
asdf = 5
class MyClass:
def myfct(self):
return asdf
I have a module which defines a complex class.
It uses a definition of the module it is in.
Here I call it asdf
.
In fact, asdf
is a class definition in itself, I just have it as an integer here for simplicity sake.
I want to remove asdf
from the module as a member, but still have the class work.
So before deleting it from the module, I first write it into the definition MyClass
dynamically after loading the module, then I delete it from the module.
import mymodule
MyClass.asdf = asdf
del sys.modules['mymodule'].asdf
Finally I use this to instantiate the new class
myobj = mymodule.MyClass()
myobj.myfct()
but of course, this throws the error
NameError: name 'asdf' is not defined
How can I make the class work without changing the code of the class, namely without changing return asdf
to return self.asdf
and but still deleting asdf
from the module (and not adding other module attributes). However, I am allowed to change the function dynamically after import mymodule
.
Keep in mind that the function definition is very complex, so something like writing it again with exec
(https://stackoverflow.com/a/11291851/4533188) is not an option.
One idea of mine is to change the signature of the method dynamically such that it receives an optional argument asdf
. That way, the code inside would use that variable, but I do not know how to do that. Possibly helpfull might be Byteplay/Metaclasses: