1

I want to use name of arguments in argparse as variable names. Now I'm doing something like:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('a')
parser.add_argument('b')
parser.add_argument('c')
parser.add_argument('--d')
parser.add_argument('--e')

args = parser.parse_args()

a = args.a
b = args.b
c = args.c
d = args.d
e = args.e

But this is so inefficient and I may end up with over 10 arguments in total. Is there an efficient way to do this?

2 Answers2

0

This is best I have found to reduce lines of code when renaming arg vars:

a,b,c,d,e = args.a, args.b, args.c, args.d, args.e

For me it's an acceptable solution, where no additional processing is required on an arg var.

refriedjello
  • 657
  • 8
  • 18
-1

Note that this is a very discouraged behavior, but if you really need to do it,

globals().update(args.__dict__)

will update your global namespace.

Ignatius
  • 2,745
  • 2
  • 20
  • 32
  • This is a bad idea. Take a look https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – Chris Feb 27 '19 at 08:42
  • 1
    @Chris, yes, I agree very much, thus "this is a very discouraged behavior." But if one has a convincing reason to do so, with enough consideration, I'm just suggesting a way to do it. (And I wouldn't count the OP's "saving typing" as a convincing reason...) – Ignatius Feb 27 '19 at 08:47
  • Thanks guys. I will definitely use it with caution. It's only an ad hoc script. –  Feb 27 '19 at 08:48