Nadodiyin Pulambal

A Wanderer Gripes

Archive for the ‘Python’ Category

Python stuff

Creating variables on the fly in Python

Posted by kovaiputhalvan on August 16, 2006

This is a dirty hack; it is not recommended to be used in “production” code. Also, I lay no claim to the originality of this hack; after I discovered it, a little googling yielded the fact that many other people have had the same brainwave.

This hack works courtesy Python’s exec statement, which allows dynamic execution of Python code; thanks are also due to the string formatting / interpolation operator, %.

#Creating a variable called "new_variable" on the fly
varname = "new_variable"
value = range(1,10)
exec "%s = %s" % (varname, value)
print new_variable

Voila!

How the hack works is more or less self-explanatory. A brief look at section 6.14 of the Python reference manual should clear doubts, if any.

I’m using this hack for a “user-friendly” – or should I say user over-friendly – interface to something. I put in the “not recommended for production code” warning because I feel this is an ugly hack. Why is this an ugly hack? I don’t know! Variables appearing out of thin air all by themselves doesn’t seem right to me! Using a sleight of hand trick to achieve the effect doesn’t seem right either.

Posted in Python, stuff | 2 Comments »