Questions tagged [python-closures]

A Python closure is a nested function which has access to a free variable from an enclosing function that has finished its execution.

A Python closure is a nested function which has access to a free variable from an enclosing function that has finished its execution.

7 questions
161
votes
10 answers

How do lexical closures work?

While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) Note that…
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
11
votes
2 answers

What does "late binding closures" mean?

I have a back-ground of C++ and trying to learn some python. Whilst i understand virtual functions for C++, I unfortunately do not understand what is meant by late binding of closures in python. Link:…
Bobo
  • 245
  • 2
  • 10
1
vote
1 answer

Why does python use intermediate cell for closures?

guys i quite don't understand why python uses intermediate cell for closures. For example: def outer(): x = "world" def inner(): print(f"Hello {x}") return inner Now both x.outer and x.inner (disregard dot notation, that's just to…
1
vote
1 answer

Python variable scope - outer exception variable undefined if used in inner exception

Can someone please help me understand what is happening here. I have some understanding on how scope of variables work in python. When this code runs, I get an error: rec = True try: print("outer try") raise Exception("outer…
MagnumCodus
  • 171
  • 1
  • 11
0
votes
0 answers

Python Closures is not passing the value of a scaler to Keras loss function

I used python Closures to enable me to pass additional argument (a scaler value) to a Keras custom loss function. This is script: @staticmethod def sdec_loss(add_loss2): def loss_function(y_true, y_pred): …
0
votes
1 answer

Decorator only works when method is decorated but not when the decorator is called with method passed as argument

Long-time listener; first time caller, so please don't shoot me if I've not perfectly followed the guidelines. So I'm trying to create a decorator which applies a status bar to a generator method. My decorator works just fine when using the…
0
votes
1 answer

Why I encounter an UnboundLocalError when I wrote a python closure, but in another similar code snippet I didn't?

I have two code snippets here. The first one, function create def creat(pos): def move(direction, step): new_x = pos[0] + direction[0]*step new_y = pos[1] + direction[1]*step pos[0] = new_x pos[1] = new_y return pos …
Raykie
  • 31
  • 5