closures

Why async function binds name incorrectly from the outer scope?

Why async function binds name incorrectly from the outer scope? Question: Here is an async function generator by iterating a for loop. I expected this closure to respect the names from the outer scope. import asyncio coroutines = [] for param in (1, 3, 5, 7, 9): async def coro(): print(param ** 2) # await …

Total answers: 2

Strange python closure variable access

Strange python closure variable access Question: While trying to implement a decorator with a closure I ran into a somewhat strange behavior, where a variable can be read, but if try to assign it later, it becomes undefined even before the assignment. def run_once(fn): to_run = True def decorated(*args, **kwargs): if to_run: print(to_run) #this access …

Total answers: 1

Python id of function of instance is inconsistent

Python id of function of instance is inconsistent Question: Please consider the following class A(object): def foo(self): pass a = A() # accessing a’s foo seems consistent init1 = a.foo init2 = a.foo assert init1 == init2 assert id(a.foo) == id(a.foo) # Or is it? foos= [a.foo for i in range(10)] ids = [id(foo) for …

Total answers: 3

Returning value in a nested function when using memoization

Returning value in a nested function when using memoization Question: I am trying to implement a count variable in the function below using dynamic programming specifically memoization. The method calculates the value in a Fibonacci sequence at a given index. I cannot figure out why the count (in this case the number of times this …

Total answers: 1

When to use nonlocal keyword?

When to use nonlocal keyword? Question: I don’t understand why I can use series variable here: def calculate_mean(): series = [] def mean(new_value): series.append(new_value) total = sum(series) return total/len(series) return mean But I can’t use count and total variables here (variable referenced before assignment): def calculate_mean(): count = 0 total = 0 def mean(value): count …

Total answers: 1

How to use returned result from inner function as a parameter in the outer function?

How to use returned result from inner function as a parameter in the outer function? Question: I have a question regarding how to use the returned result from the inner function as a parameter in the outer function. I tried the following code, but the result was not what I expected: def outer_function(a,b): def inner_function(c): …

Total answers: 3

How nonlocal keyword works?

How nonlocal keyword works? Question: In the below code, def makeAverage(): series = [] def average(newValue): series.append(newValue) total = sum(series) return total/len(series) return average python interpreter does not expect series to be nonlocal in average(). But in the below code def makeAverage(): count = 0 total = 0 def average(newValue): nonlocal count, total count += …

Total answers: 1

Schrödinger's variable: the __class__ cell magically appears if you're checking for its presence?

Schrödinger's variable: the __class__ cell magically appears if you're checking for its presence? Question: There’s a surprise here: >>> class B: … print(locals()) … def foo(self): … print(locals()) … print(__class__ in locals().values()) … {‘__module__’: ‘__main__’, ‘__qualname__’: ‘B’} >>> B().foo() {‘__class__’: <class ‘__main__.B’>, ‘self’: <__main__.B object at 0x7fffe916b4a8>} True It seems like the mere mention of …

Total answers: 2

pythonic way of composing itemgetter and attrgetter?

pythonic way of composing itemgetter and attrgetter? Question: I’ve got some code I’m porting to Cython which had a line like my_list.sort(key=lambda x: x.attr[item]) Is there a nice pythonic way of avoiding the closure with some combination of itemgetter and attrgetter? Asked By: gmoss || Source Answers: The key is to use the package functional: …

Total answers: 2

How to make imports / closures work from IPython's embed?

How to make imports / closures work from IPython's embed? Question: I sometimes use embed at a certain point in a script to quickly flesh out some local functionality. Minimal example: #!/usr/bin/env python # … import IPython IPython.embed() Developing a local function often requires a new import. However, importing a module in the IPython session …

Total answers: 3