How does argparse's add_argument take variable length arguments before keyword arguments?
Pergunta
In python2.7, the argparse module has an add_argument method which can take a variable number of unnamed arguments before its keyword arguments as shown below:
parser = argparse.ArgumentParser(description='D')
parser.add_argument('-a', '-b', ... '-n', action='store', ... <other keyword args>)
As far as I know, function definitions as follow don't work:
def fxn(var_args*, action, otherstuff):
def fxn(action, otherstuff, var_args*): # results in conflict on action
What is the proper means to emulate the add_argument
behaviour?
Solução
Python's argument definition order is...
- Required and/or default-value arguments (if any)
- variable-length positional arguments placeholder (
*<name>
if desired) - keyword arguments placeholder (
**<name>
if desired)
The positional arguments placeholder gets a list, the keyword arguments placeholder gets a dict.
add_arguments
simply looks for keys in the dict of keyword arguments, rather than spelling out all of the possible arguments in the declaration. Something along the lines of...
def add_arguments(*posargs, **kwargs):
if 'action' in kwargs:
# do something
Outras dicas
You can pass arbitrary number of arguments to a function.
Here is an example
def f(x, *args, **kwargs):
print x
for arg in args:
print arg
for key, value in kwargs:
print key + ': ' + value
Reading this will help: http://docs.python.org/tutorial/controlflow.html#keyword-arguments.