Search This Blog

Friday, April 26, 2013

How to dynamically create a variable name based on runtime conditions in Python

I needed a quick way to dynamically create local variables with a reference to my list elements. Below is an example code how to do it manually.
 
>>> l=["a","b","c","d"]
>>> l0=l[0]
>>> l0
'a'
But it is a monotone and boring task if you want to create l0, l1, l2 and so on variables. To solve this I try to play with the locals() and globals() built in functions in Python. The code below shows results.
 
>>> def f(x=1):
...  print globals()
...  print
...  print locals()
...  print
...  y=2
...  print x,y
...  print
...  print globals()
...  print
...  print locals()
...
>>>
>>>
>>> f()
{'loc': {...}, 'val': 'd', 'f': <function f at 0x2297050>, '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, 'l': ['a', 'b', 'c', 'd'], '__package__': None, 'l2': 'c', 'l3': 'd', 'l0': 'a', 'l1': 'b', '__name__': '__main__', '__doc__': None}

{'x': 1}

1 2

{'loc': {...}, 'val': 'd', 'f': <function f at 0x2297050>, '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, 'l': ['a', 'b', 'c', 'd'], '__package__': None, 'l2': 'c', 'l3': 'd', 'l0': 'a', 'l1': 'b', '__name__': '__main__', '__doc__': None}

{'y': 2, 'x': 1}

As we can see depending on the context where these functions are executed the return value is different and depends on the current runtime conditions.

The code below shows an example how to add a new variable (we could as well modify a variable value).
 
# python
>>> l=["a","b","c","d"]
>>> l0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'l0' is not defined
>>>
>>> loc=locals()
>>> loc["l0"] = l[0]
>>> loc["l1"] = l[1]
>>> loc["l2"] = l[2]
>>> loc["l3"] = l[3]
>>>
>>> l0
'a'
>>> l1
'b'
>>> l2
'c'
>>> l3
'd'

Solution

Once we put all the discovered elements together a solution to my problem is this simple code below.
 
>>> l=["a","b","c","d"]
>>> loc=locals()
>>> for k,val in enumerate(l) : loc["l"+str(k)]=val
...
>>> l0
'a'
>>> l1
'b'

References
  1. http://en.wikipedia.org/wiki/Type_introspection
  2. http://en.wikipedia.org/wiki/Reflection_(computer_science)
  3. http://stackoverflow.com/questions/4015550/create-a-new-variable-as-named-from-input-in-python
  4. http://stackoverflow.com/questions/932818/retrieving-a-variables-name-in-python-at-runtime
  5. http://www.ibm.com/developerworks/library/l-pyint/index.html
  6. http://stackoverflow.com/questions/8307612/how-to-create-class-variable-dynamically-in-python

No comments:

Post a Comment