Creating a new function as return in python function?

Question:

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?

Asked By: arynaq

||

Answers:

If you define a function inside your outer function, you can use the parameters passed to the outer function in the definition of the inner function and return that inner function as the result of the outer function.

def outer_function(*args, **kwargs):
    def some_function_based_on_args_and_kwargs(new_func_param, new_func_other_param):
        # do stuff here
        pass
    return some_function_based_on_args_and_kwargs
Answered By: Isaac

You can define functions inside functions and return these (I think these are technically closures):

def make_f(a, b):
    def x(a, b):
      return a+b
    return x(a, b) 
Answered By: foamdino

You could use a lambda (although I like the other solutions a bit more, I think 🙂 ):

>>> def func2(c, d):
...   return c, d
...
>>> def func1(a, b):
...   c = a + 1
...   d = b + 2
...   return lambda: func2(c,d)
...
>>> result = func1(1, 2)
>>> print result
<function <lambda> at 0x7f3b80a3d848>
>>> print result()
(2, 4)
>>>
Answered By: RocketDonkey

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
Answered By: dckrooney

I think what you want to do is:

def fourier_series(f,N):
    #...... math here......
    def F(x):
        #... more math here ...
        import math #blahblah, pseudo code
        return math.pi #whatever you want to return from F
    if f+N == 2: #pseudo, replace with condition where f,N turn out to be useful
        return F
    else:
        return None

Outside, you can call this like:

F = fourier_series(a,b)
if F:
    ans = F(x)
else:
    print 'Fourier is not possible :('

The important thing from Python’s point of view are:

  1. Yes, you can write a function inside a function
  2. Yes, you can return a function from a function. Just make sure to return it using return F (which returns the function object) as compared to return F(x) which calls the function and returns the value
Answered By: Anuj Gupta

While I cannot give you an answer specific to what you plan to do. (Looks like math out of my league.)

I can tell you that Python does support first-class functions.

Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable.

Cool things such as defining functions in other functions and returning functions are all possible.

>>> def func():
...     def func2(x,y):
...         return x*y
...     return func2
>>> x = func()
>>> x(1,2)
2

Functions can be assigned to variables and stored in lists, they can be used as arguments for other functions and are as flexible as any other object.

Answered By: Ijwu

I was scraping through some documentation and found this.

This is a Snippet Like your code:

def constant(a,b):
    def pair(f):
        return f(a,b)
    return pair
a = constant(1,2) #If You Print variable-> a then it will display "<function constant. 
                                                        #<locals>.pair at 0x02EC94B0>"
pair(lambda a, b: a) #This will return variable a.

Now, constant() function takes in both a and b and return a function called "Anonymous Function" which itself takes in f, and calls f with a and b.

This is called "closures". Closures is basically an Instance of a Function.

Answered By: Jenish Rudani
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.