[Tutor] monkey patching question
Danny Yoo
dyoo at hashcollision.org
Tue Feb 17 23:43:07 CET 2015
Apologies, but the answer might be unsatisfactory. The syntactic use
of decorators is confusing the situation. Let's simplify. Your
question is equivalent to the following scenario:
################################
def logged(g):
def wrapped(x):
print "call"
return g(x)
return wrapped
square = logged(lambda x: x * x)
#################################
where we can only interact with the resulting environment afterwards.
The function that you want to mock out has *already* been called by
the time you have control.
Monkey patching as a technique works only under late binding, when
there's a name that you can use to swap out an original binding with a
new one. But in the situation above, that's not applicable at all.
The function value is not being referred to by some name that's
externally accessible, so there's no handle to monkey-patch.
Can you do something else instead besides trying to monkey-patch?
Even if it were possible to do, if you can correct the original code,
that might be preferable and use less magic.
More information about the Tutor
mailing list