dynamic assigments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 24 19:05:15 EDT 2011


On Thu, 24 Mar 2011 19:39:21 +0100, Seldon wrote:

> Hi, I have a question about generating variable assignments dynamically.
[...]
> Now, I would like to use data contained in this list to dynamically
> generate assignments of the form "var1 = value1", ecc where var1 is an
> identifier equal (as a string) to the 'var1' in the list.

Why on earth would you want to do that?

Named variables are useful when you know the variable name when you are 
writing the code:

number_of_rows = 42
#... and later
for row in number_of_rows: pass

Great, that works fine. But if you don't what the variable is called when 
you are writing the code, how are you supposed to refer to it later?

s = get_string()
create variable with name given by s and value 42
# ... and later
for row in ... um... what goes here???


This sort of dynamic creation of variables is an anti-pattern: something 
you should nearly always avoid doing. The better way of dealing with the 
problem of dynamic references is to use a dict with key:value pairs:

s = get_string()
data = {s: 42}
# ... and later
for row in data[s]: pass

In this case, the string s is the key, possibly "number_of_rows". You, 
the programmer, don't care what that string actually is, because you 
never need to refer to it directly. You always refer to it indirectly via 
the variable name s.


-- 
Steven



More information about the Python-list mailing list