8

I'm using argparse in python to parse commandline arguments:

parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()

Now I want to do some calculations with a, b, and c. However, I find it tiresome to write args.a + args.b + args.c all the time.

Therefore, I'm extracting those variables:

a, b, c = [args.a, args.b, args.c]

Such that I can write a + b + c.

Is there a more elegant way of doing that?

Manual extraction gets very tedious and error prone when adding many arguments.

nalply
  • 26,770
  • 15
  • 78
  • 101
Lemming
  • 4,085
  • 3
  • 23
  • 36

2 Answers2

9

If you want them as globals, you can do:

globals().update(vars(args))

If you're in a function and want them as local variables of that function, you can do this in Python 2.x as follows:

def foo(args):
   locals().update(vars(args))       
   print a, b, c
   return
   exec ""  # forces Python to use a dict for all local vars
            # does not need to ever be executed!  but assigning
            # to locals() won't work otherwise.

This trick doesn't work in Python 3, where exec is not a statement, nor likely in other Python variants such as Jython or IronPython.

Overall, though, I would recommend just using a shorter name for the args object, or use your clipboard. :-)

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Thanks for the answer. It works, but the `exec ""` part feels like a very ugly hack. Why is that necessary? – Lemming Nov 29 '11 at 06:21
  • Correction: It does not work if the function contains nested functions. In this case the following error message pops up: `exec "" SyntaxError: unqualified exec is not allowed in function 'main' it contains a nested function with free variables` – Lemming Nov 29 '11 at 06:30
  • Ick. I did not know that, but it makes sense. Closures require Python's standard local variable mechanism, which accesses locals by index. The use of the `exec` statement anywhere in a function forces Python to use an alternate method of accessing locals by name, because `exec` could define or modify locals (this is also why you can update `locals()` if `exec` is seen in the function, but not otherwise). – kindall Nov 29 '11 at 17:18
0

You can add things to the local scope by calling locals(). It returns a dictionary that represents the currently available scope. You can assign values to it as well - locals()['a'] = 12 will result in a being in the local scope with a value of 12.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • You should not modify the return value of `locals()`. It is not guaranteed to have an effect, and usually doesn't in CPython. http://docs.python.org/library/functions.html#locals – Michael Hoffman Nov 29 '11 at 05:33
  • Seems that this doesn't work without the `exec ""` trick, that kindall mentioned. – Lemming Nov 29 '11 at 06:27