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
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
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)
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.