implicit variable declaration and access
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Jun 13 19:17:43 EDT 2005
On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote:
> Is there any reflective facility in python
> that I can use to define a variable with a
> name stored in another variable ?
> like I have :
> x = "myVarName"
>
> what can I do to declare a new variable with the name of the string
> stored in x. And how can I access that implicitly later ?
Any time you find yourself wanting to indirectly define variables like
this, the chances are you would get better results (faster, less security
risks, easier to maintain, easier to re-factor and optimise, more
readable) if you change the algorithm.
Instead of:
x = "myVarName"
create_real_variable(x, some_value)
print myVarName
why not do something like this:
data = {"myVarName": some_value}
print data["myVarName"]
It is fast, clean, easy to read, easy to maintain, no security risks from
using exec, and other Python programmers won't laugh at you behind your
back <smiles>
--
Steven
More information about the Python-list
mailing list