Search code examples
pythonhigher-order-functions

Creating a new function as return in python function?


I was wondering if it is possible in python to do the following:

def func1(a,b):
   return func2(c,d)

What I mean is that suppose I do something with a,b which leads to some coefficients that can define a new function, I want to create this function if the operations with a,b is indeed possible and be able to access this outside of func1.

An example would be a simple fourier series, F(x), of a given function f:

def fourier_series(f,N):
   ...... math here......
    return F(x)

What I mean by this is I want to creat and store this new function for later use, maybe I want to derivate it, or integrate or plot or whatever I want to do, I do not want to send the point(s) x for evaluation in fourier_series (or func1(..)), I simply say that fourier_series creates a new function that takes a variable x, this function can be called later outside like y = F(3)... if I made myself clear enough?


Solution

  • You should be able to do this by defining a new function inline:

    def fourier_series(f, N):
        def F(x):
            ...
        return F
    

    You are not limited to the arguments you pass in to fourier_series:

    def f(a):
        def F(b):
            return b + 5
        return F
    
    >>> fun = f(10)
    >>> fun(3)
    8