a function (funcA) that takes a function (funcB) and returns a function that can be evaluated to produce the same value that funcB would produce (if given the same arguments) plus 1
returned_func(x) = funcB(x) + 1
What could be the possible way of doing this? I am confused with the second part of the question as to how can a function return a value and function at the same time. Any code example would be much appreciated! Thanks!
The concept you're looking for is, essentially, a function decorator. In Python, functions are first-class objects, just like class instances are in other languages. That means that you can pass them around, just like any other object. For example:
def foo(x):
return x + 1
print(foo) # <function foo at 0x0000024202F43EA0>
bar = foo
print(bar) # <function foo at 0x0000024202F43EA0>
Here we created a reference to the function object itself. We can, using the same idea, make a function which returns a function:
def foo(x):
def inner(y):
return x + y
return inner
func = foo(5)
print(func(3)) # 8
func is assigned to the return value of foo, which is itself a function that we can evaluate. You want to return a function A that adds 1 to the result of another function, B. So, pass B to a function make_A:
def make_A(b):
def inner(x):
return b(x) + 1
return inner
def B(x):
return x
A = make_A(B)
print(A(1)) # 2
Python has excellent syntactic sugar for this type of function. See this primer for more information.
def func1(x):
#operations go here:
return(x + 1)
def func2():
#operations go here:
return(x - 1)
if func1(2) == func2(4):
print("Hooray")
Does this help? It is a demonstration of how parameters and return values can interact.
A segment like func(1) implies the return value with the parameter as 1.
Related
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
I am trying to learn about the lambda function in python. I understand the other examples given inside w3schools about the Lambda function. This example, however, I could not wrap my head around. How is it that mytripler(11) multiplies 3 by 11?
Note that there is nothing particularly special about lambda. It's just a convenient method of creating an anonymous function.
If the code had instead been written:
def myfunc(n):
def inner(a):
return a * n
return inner
It would be the exact same thing. Except now we've given anonymous function a name inner. But you'd discover that you can still write mytripler = myfunc(3) and it works the same way.
Python understands closures. If a variable is used (but not modified) inside an inner function, and there is an identically named variable defined in a containing function, then Python realizes that the inner variable refers to whatever value that outer variable has.
Let's take a step back: What is a function?
One definition could be that's a construct where you give it arguments, it does something and it returns a value (Let's ignore for now the cases where you don't give any arguments or where you don't receive any return value)
In Python, since everything is an object, this kind of construct is a value that can be assigned a name. For example:
>>> def example_function(argument):
... result = argument * 42
... return result
...
>>> other_name_for_example_function = example_function
>>> example_function(3)
126
>>> other_name_for_example_function(3)
126
>>> example_function == other_name_for_example_function
True
>>> example_function is other_name_for_example_function
True
Note that in the comparison made at the end, I do not call these functions, I just compare the value of example_function and other_name_for_example_function which in this case is the same "function mechanism".
Now, lambdas are another way to define a function but it's more restricted and the function isn't assigned a name automatically. Let's take the same example but with lambdas:
>>> example_lambda = lambda argument: argument * 42
>>> other_name_for_example_lambda = example_lambda
>>> example_lambda(3)
126
>>> other_name_for_example_lambda(3)
126
>>> example_lambda == other_name_for_example_lambda
True
>>> example_lambda is other_name_for_example_lambda
True
Now if we replace the function call of your example with its content, it would look like this:
>>> n = 3 # just you see where that value will be used
>>> mytripler = lambda a: a * n
>>> a = 11 # also to see where that value will be used
>>> mytripler(a)
33
So, in your example,
myfunc() provide a "function mechanism" as a return value. In the definition of that "function mechanism", you have inserted the value 3 which is an argument of myfunc()
You assign the name mytripler to that function returned
You call it like you would with any function
Does that help you understand?
Python
Can anyone help me to understand this code, I am new to Python, how does this function work?
def makeInc(x):
def inc(y):
return y + x
return inc
incOne = makeInc(1)
incFive = makeInc(5)
print(incOne(5)) # returns 6
print(incFive(5)) # returns 10
Higher-order functions
Functions like makeInc that in turn, return another function are called higher order functions. Usually, functions are known to accept data as input and return data as output. With higher order functions, functions instead of data, either return code as output or accept code as input. This code is wrapped into a function. In Python, functions are first class citizens which means functions, just like data, can be passed around. For instance:
myvariable = print
Notice, how I have assigned print to myvariable and how I have dropped the parentheses after print Functions without parentheses are called function objects. This means myvariable now is just another name for print:
print("Hello World!")
myvariable("Hello World!")
Both of the above statements do the exact same thing. What can be assigned to variables can also be returned from functions:
def myfunction():
return print
myfunction()("Hello World!");
Now let's look at your example:
def makeInc(x):
def inc(y):
return y + x
return inc
makeInc is a function that accepts a parameter called x. It then defines another nested inner function called inc which takes in a parameter called y. The thing about nested functions is that they have access to the variables of the enclosing function as well. Here, inc is the inner function but it has access to x which is a variable of the enclosing outer scope.
The last statement return inc returns the inner function to the caller of makeInc. What makeInc essentially is doing, is creating a custom function based on the parameter it receives.
For instance:
x = makeInc(10)
makeInc will first accept 10 and then return a function that takes in an argument y and it increments y by 10.
Here, x is a function that takes in any argument y and then increments it by 10:
x(42) # Returns 52
nonlocal
However, there is a caveat when using nested functions:
def outer():
x = 10
def inner():
x = 20
inner()
print(x) # prints 10
Here, you would assume that the last print statement will print 20. But no! When you assign x = 20 in the inner function, it creates a new local variable called x which is initialized to 20. The outer x remains untouched. To modify the outer x, use the nonlocal keyword:
def outer():
x = 10
def inner():
nonlocal x = 20
inner()
print(x) # prints 20
If you are directly reading x inside inner() instead of assigning to it, you do not need nonlocal.
What is happening here is that makeInc() returns a function handle pointing to specific implementation of inc(). So, calling makeInc(5) "replaces" the x in inc(y) to 5 and returns the callable handle of that function. This handle is saved in incFive. You can now call the function as defined (inc(y)). Since you set x=5 before, the result will be y+5.
I am reading the following tutorial about Python decorators tutorial. Everything is more or less clear except the following code:
def call_counter(func):
def helper(x):
helper.calls += 1
return func(x)
helper.calls = 0
return helper
#call_counter
def succ(x):
return x + 1
print(succ.calls)
for i in range(10):
succ(i)
print(succ.calls)
I cannot fully understand helper.calls notation. Is is just variable with no relations to helper function? Also how does succ function gets access to calls?
In Python functions are objects, that means you can set variables too.
def func():
pass
func.count = 0
print(func.count) # 0
func.count += 1
print(func.count) # 1
We can rewrite the decoration to this:
def succ(x):
return x + 1
succ = call_counter(succ)
So now you have a decorated succ. As you can see in call_counter, it actually returns a function called helper. And this helper function has one attribute named calls which is used to count calls. So now when you call succ(i), you are actually calling that helper function.
And yes that calls is just a normal variable.
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?
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
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)
>>>
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.
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
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:
Yes, you can write a function inside a function
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
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.
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)
I have a function in python that return an inner function
def parent_func(func):
def decorator(a,b):
return a + b
return decorator
for simplify lets consider this code
def in_func ( a, b)
return a*b
child = parent_func ( in_func)
Does someone know a way to get the "func" attribute of parent_func from child?
The func attribute only exists in the scope of the parent_func() function.
If you really need that value, you can expose it:
def parent_func(func):
def decorator(a,b):
return a + b
decorator.original_function = func
return decorator
Next question is, why would you want to do that?
What is the actual design problem behind this issue?
You can store it as an attribute on decorator before returning it.
>>> def parent_func(func):
... def decorator(a,b):
... return a + b
... decorator.func = func
... return decorator
...
>>> #parent_func
... def product(a, b):
... return a * b
...
>>> product.func
<function product at 0x000000000274BD48>
>>> product(1, 1)
2
You are slightly misusing decorators here. What is the point of writing a decorator which completely ignores the original function it is given?
Oh, I've also used the #foo decorator syntax, because it's cleaner. It's equivalent to what you have written, though.