4 ms·
Ignoring the strange nature of this code in the first place the more pythonic way to do it would be from functools import partial from operators import
by Spivak 3y ago
Ignoring the strange nature of this code in the first place the more pythonic way to do it would be
from functools import partial
from operators import add
add_n = [partial(add, n)) for n in range(10)]
assert add_n[5](4) == 9
Look ma, no closures.
- eru 3y ago'partial' creates a closure for you.
- Spivak 3y agoUnless you're talking philosophically how classes and closures are actually isomorphic then no, it doesn't. None of the variables in the outer scope are captured in the class instance. https://github.com/python/cpython/blob/main/Lib/functools.py#L276 https://github.com/python/cpython/blob/main/Lib/functools.py... Here's a simplified version of that code that demonstrates the pattern. class partial: def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): return self.func(*self.args, *args, **(self.kwargs | kwargs)) p = partial(add, 5) # -> an instance of partial with self.args = (5,) res = p(4) # -> calls __call__ which merges the args and calls add(5, 4)
- eru 3y agoI was talking 'philosophically' in that sense. The partial object does create a new scope that binds a few of those variables. But you are also right that the mechanisms in Python are different (on some suitable mid-level of abstraction) for those two.