7
Python has both positional and named parameters and operators *
and **
which allow receiving an arbitrary number of additional arguments:
def foo(a, b, c=1, *args, **kwargs):
print(a, b, c, args, kwargs)
foo(1, 2) # 1, 2, 1, (), {}
foo(1, 2, 3) # 1, 2, 3, (), {}
foo(1, 2, 3, 4) # 1, 2, 3, (4,), {}
foo(1, 2, 3, 4, 5) # 1, 2, 3, (4,5), {}
foo(b=1, a=2) # 2, 1, 1, (), {}
foo(b=1, a=2, c=3) # 2, 1, 3, (), {}
foo(b=1, a=2, c=3, d=4) # 2, 1, 3, (), {'d':4}
foo(b=1, a=2, c=3, d=4, e=5) # 2, 1, 3, (), {'d':4, 'e':5}
foo(1, 2, 3, 4, 5, d=6, e=7) # 1 2 3 (4, 5) {'d': 6, 'e': 7}
I would like to know whether, in such a case, you mix explicitly stated parameters with lists/sets of arbitrary arguments, whether it is possible to obtain the set of all of them, and not just the additional ones. Example:
def foo(a, b, c=1, *args, **kwargs):
print(list_args(...))
print(dict_args(...))
foo(1, 2, 3, 4, 5, d=6, e=7)
# (1, 2, 3, 4, 5, 6, 7)
# {'a':1, 'b':2, 'c':3, 3:4, 4:5, 'd':6, 'e':7}
(only one example; such a feature could have additional restrictions - such as not mixing *args
with **kwargs
, or represent the arguments in a different way - but the interesting thing is that something like this existed/could be done)
Is it possible? Compare with the Javascript language, which allows both named parameters and access to the list of all arguments via arguments
:
function foo(a, b, c) {
console.log(arguments);
}
foo(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]
// Repare que o conjunto inclui "a", "b" e "c", ao contrário do Python
Note: the motivation of this question is to find a way to create a function that has a well defined set of parameters (with exact number and names, and maybe optional values) but can pass on all of them (after some validation, or even change) to another function that has exactly the same parameters.
I swear I still don’t understand the motivation of this. If it’s all accurate, why do you need to do this kind of validation?
– ppalacios
@Palaces The motivation is to assist in the creation of decorators (the design pattern, not necessarily the syntactic construction). A practical example - not necessarily the best - would be to create a signature function identical to a model in Django, validate the data received (business rules) and then pass it on to
objects.create
without having to explicitly list each argument.– mgibsonbr