Python的argparse:如何使用关键字作为参数名称 [英] Python's argparse: How to use keyword as argument's name

查看:87
本文介绍了Python的argparse:如何使用关键字作为参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lambda在Python中具有关键字功能:

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 escape sequence or another way?

您可能会问为什么我不使用其他名字.这是因为我想使用 argparse :

You may ask why I don't use another name. This is because I'd like to use 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)
args = parser.parse_args()

print args.lambda # syntax error!

使用--help选项调用的脚本给出:

Script called with --help option gives:

...
optional arguments
  -h, --help            show this help message and exit
  -l LAMBDA, --lambda LAMBDA
                        Defines the quantity called lambda

因此,我想保留lambda作为变量名.解决方案也可能与argparse相关.

Because of that, I would like to stay with lambda as the variable name. Solutions may be argparse-related as well.

推荐答案

您仍可以使用动态属性访问来访问该特定属性:

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

print getattr(args, 'lambda')

更好的是,告诉argparse使用其他属性名称:

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

dest参数告诉argparse使用lambda_作为属性名称:

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

print args.lambda_

当然,帮助文本仍将参数显示为--lambda;我显式设置了metavar,否则将大写使用dest(因此带有下划线):

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

这篇关于Python的argparse:如何使用关键字作为参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆