I know how to override methods:
class Foo(object):
def bar(self):
return True
def damn_monkeys(self):
return False
Foo.bar = damn_monkeys
Is it possible to achieve something similar with functions?
def foo(arg1):
def bar(arg2):
return 1
return bar(arg1)
foo.bar = monkeys # doesn't work as bar obviously isn't an attribute
I have found some hooks (func_code
), but those seem to be solely for the inspector and it seems rather dubious to fiddle with them.
I also noticed functions have an __init__
and __call__
reference, but those seem to point to the __builtin__.__function
object. I haven't inspected further but it seems functions are objects too (which makes sense reading everything in python is an object). I suppose functions are already instances of the __function
object, and thats why foo.__init__
doesn't raise an error, however its never touched by the debugger.
Is there any way to override an inner function without copying or patching the code?
edit duplicate with answer: Can you patch *just* a nested function with closure, or must the whole outer function be repeated?