-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
BoundArguments facility to inject defaults #68378
Comments
The recipe to inject default values in a BoundArguments instance is given in the doc, but it's not trivial. Furthermore, it's actually incomplete: it doesn't handle any star-arguments, e.g.: >>> sig = inspect.signature(f)
>>> ba = sig.bind(2, d=4)
>>> for param in sig.parameters.values():
... if (param.name not in ba.arguments
... and param.default is not param.empty):
... ba.arguments[param.name] = param.default
...
>>> ba.arguments
OrderedDict([('a', 2), ('d', 4), ('b', 5)]) ba['c'] would ideally contain the empty tuple. |
My example forgets the function declaration, which is: >>> def f(a, b=5, *c, d=5): pass
... |
See bpo-22998. The more complete and thus more complex example in the last message makes it look like including this in the library might be a good idea. |
Well, the docs example only binds explicit defaults in function signature. Implicit defaults for *args and **kwargs ( Do you guys have any good use case for such method? I use the Signature API extensively for argument types validation and for serialization of RPC calls, but I never needed this functionality from BoundArguments. |
Le 14/05/2015 17:45, Yury Selivanov a écrit :
When the defaults are filled I expect ba.arguments to be "complete",
A use case was given in bpo-22998. |
This is a great use case ;-) Let's add it. I propose the following method: BoundArguments.apply_defaults() It will iterate through its parent Signature's parameters and assign default values to BoundArguments.arguments (when an arg is missing), including setting '()' for *args, and '{}' for **kwargs. If you're OK with this, I can draft a patch. |
That sounds good to me, thank you! |
FWIW it wasn't as easy as I thought it would be :) You were right, docs example is very basic. Please take a look at the attached patch. |
New changeset ea61d8eb8a28 by Yury Selivanov in branch 'default': |
Thanks for the suggestion, Antoine! |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: