Since Python's functions are first-class citizens, a function can itself define a new function and return it. Defining a function inside a function can be done with def
in the same way it would be in you top scope.
As a sidenote, I recommend you do not use compile
as a function name as it does not accurately reflect what you are trying to do, which is called function composition, as well as overwrite the builtin function compile
.
def compose_with_self(f, n):
def composed(arg):
for _ in range(n):
arg = f(arg)
return arg
return composed
Example:
def add_one(x):
return x + 1
add_three = compose_with_self(add_one, 3)
print(add_three(1)) # 4