implicit variable declaration and access

Ali Razavi arazavi at swen.uwaterloo.ca
Tue Jun 14 11:48:14 EDT 2005


Steven D'Aprano wrote:
> 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>
> 
> 
I ain't writing a real program, just summarizing a few languages
(Python, Smalltalk, Ruby, ...) meta programming facilities and compare 
them with each other, it will only be an academic paper eventually. Thus 
I am only trying out stuff, without worrying about their real world 
consequences. And yes you are right, I am not a Python programmer, well 
to be honest, I am not a real "any language" programmer, as I have never 
written any big programs except my school works, and I don't even intend
to become one, Sorry it's just too boring and repetitive, there are much
more exciting stuff for me in computer engineering and science than 
programming, so I will leave the hard coding job to you guys and let you 
laugh behind the back of whoever you want!
Have a good one!




More information about the Python-list mailing list