Reputation: 2999
I want to run a third-party python program thirdparty.py
the way I want. I CANNOT change the code of thirdparty.py
directly, so I change the external module used by thirdparty.py
. The code of thirdparty.py
is like:
import module_a
def somefunc():
...
module_a.add(value)
So I create my own module_a.py
and rewrite its add(value)
function:
# module_a.py created by me
def add(value):
# code written by me
do_something()
Now my problem is, how can I remember the value
everytime module_a.add(value)
is invoked by thirdparty.py
?
My current workaround is to write the value
back to an external file in do_something()
. However, I don't want any external file and I/O involved. Also, I can neither use a class in module_a.py
to maintain the states, nor change the signature of add(value)
, otherwise module_a.add(value)
in thirdparty.py
won't work.
Ideally I want to write another class to interact with module_a.py
and remember the value passed to add(value)
everytime, but how to do this?
Upvotes: 1
Views: 1304
Reputation: 1275
The solution to your question as asked is here. You can set internal variables for python functions like so:
def add(value):
# code written by me
add.state = add.state+1
do_something()
add.state = 0
Upvotes: 1