How does argpse add_argument accept variable-length arguments before keyword arguments?

In python2.7, the argparse module has an add_argument method that 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, the function definitions below do not work:

def fxn(var_args*, action, otherstuff):
def fxn(action, otherstuff, var_args*): # results in conflict on action

What are the proper ways to emulate behavior add_argument?

+3
source share
2 answers

The order in which Python arguments are defined ...

  • Mandatory and / or default arguments (if any)
  • placeal arguments placeplace arguments of variable length ( *<name>optional)
  • keyword arguments placeholder ( **<name>optional)

, arguments placeholder dict.

add_arguments , , . - ...

def add_arguments(*posargs, **kwargs):
    if 'action' in kwargs:
        # do something
+3

.

def f(x, *args, **kwargs):
    print x
    for arg in args:
        print arg
    for key, value in kwargs:
        print key + ': ' + value

: http://docs.python.org/tutorial/controlflow.html#keyword-arguments.

+2

Source: https://habr.com/ru/post/1780337/


All Articles