Entry
Is there a way to create variables on the fly, like in a loop?
May 22nd, 2003 06:56
Clark Updike, unknown unknown, Michal Wallace
Problem:
Does anyone know of a way to create variables on the fly, like in a
loop? I want to be able to build a set of check buttons in a GUI I'm
writing, and each check button needs a different variable, I think, to
determine which ones are checked. I want to use a for loop to iterate
over a list to build the check buttons, but I don't know the contents
or
length of the list.
Solution:
The concept is called anonymous objects. In python, objects can have
more than one reference pointing to them. Some of those references
have names, or labels that you can see in the code. eg:
>>> x = SomeClass()
.. That creates a SomeClass instance and calls it "x". But
you can then say:
>>> y = [x]
.. And now y[0] references the same SomeClass instance.
if you then say:
>>> x = None
.. y[0] is STILL REFERENCING the original SomeClass instance.
It's just "anonymous" now because it doesn't have a specific
name. You could just as easily have said:
>>> y = [SomeClass()]
and if you want more than one:
>>> y = []
>>> for x in range(10):
... y.append[SomeClass()]
Here's some psuedocode that might get you thinking:
>>> btnLst = []
>>> for x in range(whatever):
... newBtn = SomeButton() # just create the widget
... btnValue = SomeValue() # read from a list, maybe?
... newBtn.pack() # or whatever to get it on the screen
... list.append((newBtn,btnValue)
and later on:
>>> for button in btnLst:
... if button.isChecked:
... DoWhatever()
This may be close to what your trying to do:
>>> def alias(obj, name, namespace):
... namespace[name]=obj
...
>>> x = [1,2,3]
>>> alias(x, 'y', globals())
>>> y
[1, 2, 3]
>>> y is x
1
>>> y[0]=-1
>>> x
[-1, 2, 3]
>>>
Obviously, name will clobber a variable in globals() with the same name,
just like:
>>> y = 1
clobbers 1 when you do:
>>> y = 2