Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argparse and "in" option

I have what I think is a trivial issue, but was not able to find the reply.

I have a very simple argparse script:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--in', help='Input folder', default='../../in')
parser.add_argument('--out', help='Output folder', default='../../out')
args = parser.parse_args()
print(f'From {args.in} to {args.out}')

This results in an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  File "[...]\__main__.py", line 16
    (args.in)
          ^^
SyntaxError: f-string: invalid syntax

The issue, however, is only with the in parameter; if I remove it from the f-string the out parameter is printed successfully.

If I try to print the args variable I get

Namespace(in='../../in', out='../../out')

which means that the in parameter is read. I assume the .in way is reserved, but then… how do I access it?

If it is useful, I’m using Python 3.10.4 on Windows

>Solution :

You cannot – Why can’t attribute names be Python keywords?

But, at the parsing level, you can specify dest argument, which will change the name that is assigned to the command line argument in Python.

parser.add_argument('--in', dest = "_in", help='Input folder', default='../../in')

print(f'From {args._in} to {args.out}')

This way you can still start the program with --in ... --out ... arguments without breaking the code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading