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 would expect to see:
dynamic
but I see
predefined
Why? How can I get the dynamic value instead?
Update:
The reason why I ask: I have a program that takes many input arguments, with lengthy variable names. I was hoping to simply "unpack" whatever the argparse
parser receives in a single call to locals().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