[Tutor] Addressing a variable whose name is the value of a string

Andreas Pfrengle spelzdinkelclonk at web.de
Mon Apr 9 17:53:38 CEST 2007


Bob Gailer wrote:

> Andreas Pfrengle wrote:
>
>> [snip]
>
>> looks good if I'm happy with my values inside mydict and don't want 
>> to have sth. like x=5 in the end. But since 'x' is the name of a 
>> database field (I simplified it here for an example), I still see no 
>> way around the exec, so I can change the content of the x-field 
>> (consider the content of the var-field as a vector to the 
>> corresponding field that needs a change, x in the example).
>> If this is still possible with a dict, I still don't see it (sorry), 
>> but it would surely be more elegant than an exec-solution, since I 
>> don't need security checks for the string that is saved, before 
>> executing it.
>
> I'd love to help, but am confused. If your code (at least the relevant 
> part) is of reasonable size, would you post it?
>
> Or at least some pseudo-code so I can follow your algorithm?
>
Since I'm still considering the way my db has to look, the mentioned 
problem was already thought in advance to what I will have to solve, so 
real db-interaction code doesn't exist yet. I'm using the django 
framework for this, so the essential parts might later look sth. like:

# Accessing db (see http://www.djangoproject.com/documentation/db-api/):
myobj = MyModel.objects.get(<some filter>)
var = myobj.vector
# vector is a Textfield, so var now contains a string, naming another 
db-field of myobj

execstr = "attr = myobj." + var
exec execstr
# attr now contains the content of the field named in var (an int in my 
case)
attr += 42    #some calculation with attr

execstr = "myobj." + var + " = attr"
exec execstr
myobj.save()
#the newly calculated value is now saved back to the desired field

(This is still simplified, since the vector can also reach other models, 
so there has to be more programming logic in the end)


More information about the Tutor mailing list