I have a directory with my_class.py
class MyClass:
def __init__(self):
self.a=1
def message(self):
print("message =",self.a)
I run the following code in a notebook:
from my_class import MyClass
MyClass().message() #outputs "message = 1"
Suppose now I edit my_class.py
to replace self.a=1
with self.a=2
. I would like to define a function
def my_reload(cls):
# do something
such that running
my_reload(MyClass)
MyClass().message() #I want this to now output "message = 2"
would output 2 instead of 1. How do I do that?
For example, the following code still outputs 1:
import importlib
from inspect import getmodule
def my_reload(cls):
module=getmodule(cls)
importlib.reload(module)
And this
from inspect import getmodule
def my_reload(cls):
module=getmodule(cls)
__import__(module.__name__+"."+cls.__name__)
raises ModuleNotFoundError: No module named 'my_class.MyClass'; 'my_class' is not a package
.
P.S. I would like to keep my import statement from my_class import MyClass
as is.
UPD: This works, but feels slightly evil:
import importlib
from inspect import getmodule
def my_reload(cls):
module=getmodule(cls)
importlib.reload(module)
eval("exec('from %s import %s')"%(module.__name__,cls.__name__))
return eval(cls.__name__)
MyClass=my_reload(MyClass)
MyClass().message() #outputs "message = 2"
Is there a better solution?