Let's say I have two modules:
a.py
value = 3
def x()
return value
b.py
from a import x
value = 4
My goal is to use the functionality of a.x
in b
, but change the value returned by the function. Specifically, value
will be looked up with a
as the source of global names even when I run b.x()
. I am basically trying to create a copy of the function object in b.x
that is identical to a.x
but uses b
to get its globals. Is there a reasonably straightforward way to do that?
Here is an example:
import a, b
print(a.x(), b.x())
The result is currently 3 3
, but I want it to be 3 4
.
I have come up with two convoluted methods that work, but I am not happy with either one:
- Re-define
x
in moduleb
using copy-and paste. The real function is much more complex than shown, so this doesn't sit right with me. Define a parameter that can be passed in to x and just use the module's value:
def x(value): return value
This adds a burden on the user that I want to avoid, and does not really solve the problem.
Is there a way to modify where the function gets its globals somehow?