6

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?

2
  • You may want to explain why you think it is important to have that variable name. Your code won't execute any different if the variable was named from_, but you'd have an easier time of reading your code without the work-arounds that requires.
    – Martijn Pieters
    Jul 1, 2017 at 9:37
  • Disclaimer: I am not encouraging the following method, I'm just pointing out the possibilities. In your situation I would definitely go with using from_ as the variable name. Similar to this answers you can modify the Python source (the source code of the compiler) in order to change the reserved keyword from to something else (for example from_). Then you can rebuild the source in order to obtain your custom Python compiler with which you can use from as a variable name. Please note that this is a horrible idea for many reasons.
    – a_guest
    Jul 1, 2017 at 10:02

1 Answer 1

6

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_)
2
  • Hello @Martijn Pieters. I understand that reserved words can't be used as regular identifiers but I'd like to know the internals of the following if you'd be so kind to explain. Why does getting and setting reserved words through getattr and setattr work but not with the ordinary . dot syntax (which throws a SyntaxError). Also I have a full-blown question where I'd like to get your input on. Thank you in advance! Jun 5, 2019 at 19:18
  • 1
    @George: attribute names as stored in the instance dictionary are just strings, and as strings are not subject to the stricter rules of identifiers. When you use . notation, you can only use identifiers, and identifiers can't be the same as keywords. So with getattr() the attribute name can start with a digit, or use spaces: setattr(args, "3 foo bar baz", 42) works just fine.
    – Martijn Pieters
    Jun 5, 2019 at 20:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.