Python: Extract variables out of namespace

前端 未结 2 1420
挽巷
挽巷 2021-01-12 07:13

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

parser = ArgumentParser()
parser.add_argument(\"--a\")
parser.add_argument(\"--b\")
parser.add_         


        
相关标签:
2条回答
  • 2021-01-12 07:48

    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.

    0 讨论(0)
  • 2021-01-12 07:51

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

    0 讨论(0)
提交回复
热议问题