A Partial Keyword Argument Can Be Overridden by Its Caller
A callable assembled with functools.partial can look like a fixed policy. Its saved keyword arguments are defaults for later calls: a caller can supply the same keyword with another value. A positional argument already supplied to the original function behaves differently when a later keyword tries to fill that position again. This exercise uses a label formatter and a list. It distinguishes call…
When a callable is assembled with functools.partial, it can appear to have fixed keyword arguments. These saved keyword arguments serve as defaults for subsequent calls. However, a caller can still override these saved keywords by providing a different value.
If a positional argument has already been supplied to the original function, a later keyword argument that attempts to fill that position will not be accepted. This behavior demonstrates that a partial object exposes a mutable keywords dictionary.
The examples provided do not implement an authorization check. The Python 3.12 reference documentation outlines the library behavior observed during testing. The tests cover four scenarios: saved keyword usage when omitted, call keyword overriding saved keyword, extension of the call with a new keyword, and the mutability of the keywords dictionary.
In the first test, a partial object with a saved prefix keyword is created. When calling the partial object with only the value argument, the saved prefix is used as expected.
The second test shows that a call keyword can override a saved keyword. By providing the prefix keyword with a different value during the call, the saved prefix is overridden.
The third test confirms that a saved positional argument is not treated as a keyword default. In this case, a partial object is created with a saved left positional argument. When calling the partial object with a different left value, a TypeError is raised, indicating that the saved positional argument is not a keyword default.
The fourth test verifies that the keywords dictionary remains mutable after being modified. A partial object is created with a saved prefix keyword. After modifying the saved prefix in the keywords dictionary, the modified value is used in subsequent calls to the partial object.
Finally, the last test demonstrates that a bound mutable argument is not copied when used with partial. A list is initialized as a mutable object, and the append method is used as a partial object. When calling the partial object with an argument, the original mutable list is used, and its contents are updated accordingly.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to