Reputation: 558
I'm finding myself in a predicament where I develop a class then I create an instance of this class. These classes will often perform data and stat operations which take a long time, sometimes 20 minutes.
I'll continue to develop my class and I'll add additional methods to it. Now, how do I update the previous class instance with the new method without reinitializing the older instance of the class, which in this case would take 20 minutes?
Upvotes: 3
Views: 893
Reputation: 20450
There's a bit of an XY question here.
Your true difficulty seems to be "it takes 20 minutes for the __init__
ctor to complete."
There are several ways out of that predicament.
@lru_cache
, and let your updated / reloaded class find it that way. Use importlib.reload()
.Here is one way to exploit inheritance (copying isn't necessary, but makes it cleaner):
class FooBase:
...
# global variable for expensive computation
foo = FooBase()
class FooFeature(FooBase):
def __init__(self, foo):
...
def some_new_feature(self):
...
foo = FooFeature(foo.copy()) # This happens quickly.
Here is one way to monkeypatch:
class Foo:
...
foo = Foo()
FooOriginal = Foo
# Now you edit in a brand new Foo feature and reload the class definition:
def new_feature(self):
...
FooOriginal.new_feature = Foo.new_feature
When monkeypatching,
note that foo
holds a reference to the same class object that FooOriginal
holds.
Upon reloading, Foo
becomes a brand new object,
with one additional method.
The final monkeypatch assignment
makes that method available to FooOriginal
,
and hence available to foo
.
Upvotes: 2