Understanding Function Closures [duplicate] - python

This question already has answers here:
Why aren't python nested functions called closures?
(10 answers)
Closed 8 years ago.
I'm struggling to understand Function closures properly. For example in the code below I am unclear as to how the function knows that in the statement times3(2) that x=2? Also, after reading documentations I still can't fully understand the purpose of closures.
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
times3 = make_multiplier_of(3)
times3(2) #How does the function know that x=2 here?
Thanks a lot

When you are calling make_multiplier_of(3), the function is returning multiplier such that
def multiplier(x):
return x*3
So times3 = make_multipiler(3) is assigning this particular multiplier function to times3. The same way that when you are doing myLength=len, myLength is the len function and you can call myLength("foo")
times3 is thus this multiplier function. So when you times3(2), you are doing (this particular) multiplier(2)

Related

How can a variable be used as a function? I can't understand this lambda example [duplicate]

This question already has an answer here:
Higher order function Python walkthrough
(1 answer)
Closed 7 months ago.
I was going through w3schools' writeup on Python lambdas and came across this example:
def myfunc(n): #Statement-1
return lambda a : a * n #Statement-2
mydoubler = myfunc(2) #Statement-3
print(mydoubler(11)) #Statement-4
It says that this code will print 22 as the output.
I am unable to wrap my head around statements-3 and 4 in this code... isn't mydoubler in statement-3 a variable? How can it be used as a function in statement-4?
You can use the substitution model to understand this. The substitution process is as follows:
mydoubler(11)
myfunc(2)(11)
(lambda a:a*2) (11)
11*2
22

Question about the wrapper in a decorator [duplicate]

This question already has answers here:
How do I make function decorators and chain them together?
(20 answers)
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 11 months ago.
I learne d (or tried to learn) decorators recently with python. I've coded this, but I actually don't fully understand how it actually works...
The code:
def logging_decorator(fn):
def wrapper(*args, **kwargs):
print(f"You called {fn.__name__}{args}")
result = fn(args[0], args[1], args[2])
print(f"It returned: {result}")
return wrapper
#logging_decorator
def a_function(a, b, c):
return a * b * c
a_function(1, 2, 3)
My question: I dont understand how in the wrapper the args become the inputs (a,b,c) of the function "a_function". it looks like magic to me I don't see how the inputs of the wrapper became those of the function "a_function".
My research:
I've watched 3 videos on the subject but none of them really focuses on that aspect of the problem. I've asked on other forums but still didn't get a satisfactory answer. I guess people just assume it's obvious for them it should be to others as well, but as far as I'm concerned it is not! I've had no problem using decorators in the past and understanding until I've tried to add inputs in the wrapper (trying to get the parameters of the function that we fetch to the decorator).
you're answer will be highly appreciated and I thank you in advance!

After recursion list not emptying [duplicate]

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 2 years ago.
I'm doing some discrete mathematics stuff for a teacher, he asked me to try and do everything recursively. For some strange reason the list i'm using for a function is the same as it was the last time I called the function.
Here's my code:
def extended_euclidean_algorithm(a:int, b:int, equations=list()):
#This line is just for debugging and checking that my hipothesis was correct
print (len(equations))
if b==0:
return
if a<b:
b,a=a,b
quotient=a//b
remainder=a%b
equations.append(f"{a}={quotient}*{b}+{remainder}")
if extended_euclidean_algorithm(b, remainder, equations):
return equations
for i, equation in enumerate(equations):
equations[i]=equation.split('+')
equations[i][0]=equations[i][0].split('=')
equations[i][0]="-".join(equations[i][0])
equations[i]='='.join(equations[i])
return True
First time I call it, it's Ok. But second time I call it includes the numbers from the last time I called it.
Since you set the list in the arguments, by default the list exists and can be appended to.
You better use:
def extended_euclidean_algorithm(a:int, b:int, equations=None):
equations = equations if equations else []
In this way, equations - if not set - is None rather than an empty list.
Check out the pythontutor visualization here:

Understanding how does a decorator really work [duplicate]

This question already has answers here:
How do I make function decorators and chain them together?
(20 answers)
Closed 4 years ago.
I'm starting studying decorators and I already hit an obstacle. First here is my code.
def deco (f):
def coucou():
print("this is function{}".format(f))
return f()
return coucou
#deco
def salut():
print("salut")
def hi():
return salut()
I will try to explain my problem as well as I can with my bad English. If I understand it this is how things should happen: I execute my hi() function which returns salut() and because salut is modified by the decorator coucou will be executed and coucou returns ....... salut(), what i mean is that I expect an infinite loop but that doesn't happen and I don't understand why. Can anyone explain practically how decorators work?
The f in coucou is the undecorated (original) version of salut.

How do return values work? [duplicate]

This question already has answers here:
I need help wrapping my head around the return statement with Python and its role in this recursive statement
(2 answers)
Closed 8 years ago.
def fudz(n):
if n <= 2:
return 1
print("nom" * n)
return fudz(n-1) + fudz(n//2)
result = fudz(4)
Can someone give me a step by step of this function?
This is a recursive function, which means it calls an instance of itself on a simplified instance of the problem until it gets to a base case for which it already knows the answer. Remember that any call to a function occurs in its own stack frame, so it's going to have its own value for n.
You can walk through it yourself. First, think about what happens when n==2. Then think about n==3, and increase n until it makes sense to you.

Categories