3 ms·
Yes. The usual way to do this is to bind them as defaults to an argument, for example: def loop(): for number in range(10): def func_w
by nbadg 2y ago
Yes. The usual way to do this is to bind them as defaults to an argument, for example:
def loop():
for number in range(10):
def func_w_closure(_num=number):
return _num
yield func_w_closure
This works because default arguments in python are evaluated exactly once, at function definition time. So it's a way of effectively copying the ``number`` out of the closure[1] and into the function definition.
[1] side note, closures in python are always late-binding, which is what causes the behavior in OP
- NwtnsMthd 2y agoDoes this work for user defined classes (objects) as well?
- Jtsummers 2y agoYes, and by the same mechanism and for the same reason.
- amluto 2y agoI’ve never thought that leaking this type of implementation detail into the return value (and return type!) was a nice solution. I like the double closure better, and one can shorten it a bit with a lambda. For those who prefer a functional style, functools.partial can also solve this problem. (I use Python, and I like a lot of things about Python, but I don’t like its scoping rules at all, nor do I like the way that Python’s closures work. I would use a double lambda.)
- deleted 2y ago[deleted]