How to use reserved keyword as the name of variable in python?

只谈情不闲聊 提交于 2019-12-10 23:19:47

问题


I want to use reserved keyword "from" as the name of variable.

I have it in my arguments parser:

parser.add_argument("--from")
args = parser.parse_args()
print(args.from)

but this isn't working because "from" is reserved. It is important to have this variable name, I don't want answers like "from_".

Is there any option?


回答1:


You can use getattr() to access the attribute:

print(getattr(args, 'from'))

However, in argparse you can have the command-line option --from without having to have the attribute from by using the dest option to specify an alternative name to use:

parser.add_argument('--from', dest='from_')

# ...
args = parser.parse_args()
print(args.from_)


来源:https://stackoverflow.com/questions/44859431/how-to-use-reserved-keyword-as-the-name-of-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!