Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Extract variables out of namespace

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.

like image 217
Lemming Avatar asked Nov 29 '11 05:11

Lemming


1 Answers

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. :-)

like image 130
kindall Avatar answered Sep 28 '22 05:09

kindall