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

Question:

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?

Asked By: Július Marko

||

Answers:

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_)
Answered By: Martijn Pieters