1

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?

Ida
  • 2,919
  • 3
  • 32
  • 40
  • What do you mean remember the value? What do you want to do with the remembered value? – Anand S Kumar Jul 17 '15 at 03:40
  • I think you might have [XY Problem](http://www.perlmonks.org/?node=XY+Problem) here. Why can't you wrap thirdparty.py in a module you wrote? Do you want to track module_a calls? – Jeremy Kemball Jul 17 '15 at 03:43
  • When `module_a.add()` gets called it will be called with a new value -- why do you need to remember the old value? And which old value do you want? – Ethan Furman Jul 17 '15 at 04:41

1 Answers1

1

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
Community
  • 1
  • 1
Jeremy Kemball
  • 1,175
  • 1
  • 9
  • 14