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?

Július Marko
  • 1,196
  • 5
  • 15
  • 37
  • 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 01 '17 at 09: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](https://stackoverflow.com/a/9108164/3767239) 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 01 '17 at 10:02

1 Answers1

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_)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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](https://stackoverflow.com/questions/56459573/should-you-use-the-underscore-as-an-access-modifier-indicator-in-non-library/56460331#comment99523097_56460331) where I'd like to get your input on. Thank you in advance! – Marius Mucenicu Jun 05 '19 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 05 '19 at 20:31