Python: Redefine function so that it references its own self

3373 views python
-2

Say I have got some function fun, the actual code body of which is out of my control. I can create a new function which does some preprocessing before calling fun, i.e.

def process(x):
    x += 1
    return fun(x)

If I now want process to take the place of fun for all future calls to fun, I need to do something like

# Does not work
fun = process

This does not work however, as this creates a cyclic reference problem as now fun is called from within the body of fun. One solution I have found is to reference a copy of fun inside of process, like so:

# Works
import copy
fun_cp = copy.copy(fun)
def process(x):
    x += 1
    return fun_cp(x)
fun = process

but this solution bothers me as I don't really know how Python constructs a copy of a function. I guess my problem is identical to that of extending a class method using inheritance and the super function, but here I have no class.

How can I do this properly? I would think that this is a common enough task that some more or less idiomatic solution should exist, but I have had no luck finding it.

answered question

1 Answer

0

This looks like a use case for python's closures. Have a function return your function.

def getprocess(f):
    def process(x):
        x += 1
        return f(x)  # f is referenced from the enclosing scope.

    return process

myprocess = getprocess(fun) 
myprocess = getprocess(myprocess) 

posted this

Have an answer?

JD

Please login first before posting an answer.