*
and **
operators that allow you to receive 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 wonder if in a case like this, you mix explicitly declared parameters with arbitrary argument lists / sets, if you can get the set of all of them , 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}
(just one example, such a feature could have additional constraints - such as not mixing *args
with **kwargs
, or representing the arguments in a different way - but interestingly something like that 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 for 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 all of them (after some validation, or even change ) to another function that has exactly the same parameters.