Skip to content
Advertisement

Are these `.` attribute bindings necessary in the implementation of `functools.partial`?

docs.python.org says that functools.partial is roughly equivalent to:

JavaScript

(Note: / is used to denote func as a positional-only argument of partial. See [1].)

If I understand correctly, when a variable is referenced within a nested function, such as newfunc, Python first looks for the variable definition within the nested function. If the definition is not found there, Python will next look for the definition in the enclosing scope (i.e. the outer function; partial in this case). So, are the explicit .func, .args, and .keywords attribute bindings to newfunc above really necessary? I tried an example without said bindings and it partial worked just fine? Is there a case where they might be necessary?

JavaScript

Are the . bindings necessary if the keywords or fkeywords dictionaries includes an item with func, args, or keywords as the keyword? What would be an example where these are necessary? As far as I can tell, that’s not a reason because the following works:

JavaScript

[1] https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters

Advertisement

Answer

I think you can look at the partial class implementation to help you understand better.

The following (Python 3.9.5)

JavaScript

When you replace self with newfunc, they’re pretty much the same.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement