Python's argparse: How to use keyword as argument's name

后端 未结 3 1919
鱼传尺愫
鱼传尺愫 2021-01-18 00:30

lambda has a keyword function in Python:

f = lambda x: x**2 + 2*x - 5

What if I want to use it as a variable name? Is there an

相关标签:
3条回答
  • 2021-01-18 00:38

    You can use dynamic attribute access to access that specific attribute still:

    print getattr(args, 'lambda')
    

    Better still, tell argparse to use a different attribute name:

    parser.add_argument("-l", "--lambda",
        help="Defines the quantity called lambda",
        type=float, dest='lambda_', metavar='LAMBDA')
    

    Here the dest argument tells argparse to use lambda_ as the attribute name:

    print args.lambda_
    

    The help text still will show the argument as --lambda, of course; I set metavar explicitly as it otherwise would use dest in uppercase (so with the underscore):

    >>> import argparse
    >>> parser = argparse.ArgumentParser("Calculate something with a quantity commonly called lambda.")
    >>> parser.add_argument("-l", "--lambda",
    ...     help="Defines the quantity called lambda",
    ...     type=float, dest='lambda_', metavar='LAMBDA')
    _StoreAction(option_strings=['-l', '--lambda'], dest='lambda_', nargs=None, const=None, default=None, type=<type 'float'>, choices=None, help='Defines the quantity called lambda', metavar='LAMBDA')
    >>> parser.print_help()
    usage: Calculate something with a quantity commonly called lambda.
           [-h] [-l LAMBDA]
    
    optional arguments:
      -h, --help            show this help message and exit
      -l LAMBDA, --lambda LAMBDA
                            Defines the quantity called lambda
    >>> args = parser.parse_args(['--lambda', '4.2'])
    >>> args.lambda_
    4.2
    
    0 讨论(0)
  • 2021-01-18 00:42

    argparse provides destination functionality for arguments if the long option name is not the desired attribute name for the argument.

    For instance:

    parser = argparse.ArgumentParser()
    parser.add_argument("--lambda", dest="function")
    
    args = parser.parse_args()
    
    print(args.function)
    
    0 讨论(0)
  • 2021-01-18 00:43

    There is an argparse-specific way of dealing with this. From the documentation:

    If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars().

    Therefore, you should be able to write:

    print vars(args)["lambda"]  # No keyword used, no syntax error.
    
    0 讨论(0)
提交回复
热议问题