Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

'partial' creates a closure for you.


Unless 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...

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)


I 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: