Updating locals () that have a predefined value

Consider the following example:

def main():
  a = 'predefined'

  variables = {'a':'dynamic'}
  locals().update(variables)

  print a

if __name__ == '__main__':
    main()

When running the script, I expect to see:

dynamic

but i see

predefined

Why? How can I get a dynamic value instead?

Update:

The reason I ask: I have a program that takes a lot of input arguments with long variable names. I was hoping to just “unzip” everything the parser receives argparsein one calllocals().update(...)

def main():
  a = 'predefined'
  parser = argparse.ArgumentParser(description='My program')
  parser.add_argument('-a', type=int, default=a,  required=False);

  # Hoping to avoid typing lines like the following for every parameter:
  # a = parser.parse_args().a

  input_variables = vars(parser.parse_args())
  locals().update(input_variables)

  # Process stuff using the parameter names directly, e.g. 
  print a
+3
source share
2 answers

It is mentioned in the documentationlocals :

Note . The content of this dictionary should not be changed; changes may not affect the values ​​of local and free variables used by the translator.

AFAIK, / .

+6

locals()? obj.var_name. , var_name, , exec.

from copy import copy


class Empty(object):
    pass


def main():
    a = 'predefined'
    b = 'predefined'
    loc = copy(locals())
    variables = {'a':'dynamic'}
    loc.update(variables)
    obj = Empty()
    for k, v in loc.items(): #iteritems for Python 2
        setattr(obj, k, v)

    print(obj.a, obj.b) # print statement for Python 2
0

All Articles