storing variable names in a list before they are used?

Hendrik van Rooyen mail at microcorp.co.za
Sun Oct 1 05:23:54 EDT 2006


"Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote:

> On Sat, 30 Sep 2006 14:33:35 -0400, John Salerno
> <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python:
>
> >
> > Ok, I'm sure you all get the idea by now, but here's a simpler way to
> > look at it:
> >
> > Instead of
> >
> > first_name = wx.TextCtrl(self)
> > last_name = wx.TextCtrl(self)
> > job_title = wx.TextCtrl(self)
> > etc.
> >
> > and subsequently:
> >
> > sizer.Add(first_name)
> > sizer.Add(last_name)
> > sizer.Add(job_title)
> > etc.
> >
> > I want to do something like this:
> >
> > for name in names:
> >      name = wx.TextCtrl(self)
> >      sizer.Add(name)
> >
> > It's just that I don't know how to handle the "name" variable in the
> > "names" list.
>
> Short blunt answer... You Don't

Longer, less blunt answer:

You could, if you wanted to, write:

errfile = "name_of_error_file_for_compile_statement"
expr = name+" = wx.TextCtrl(self)"
eval(compile(expr, errfile,'single'))

and the name that reads the same as the text string should be created.

To access it, you can then use:

sizer.Add(eval(name))

Example:

IDLE 1.1.3      ==== No Subprocess ====
>>> banana
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in ?
    banana
NameError: name 'banana' is not defined
>>> name = "banana"
>>> errfile='errfile'
>>> expr = name+'="A yellow sickle shaped fruit"'
>>> eval(compile(expr,errfile,'single'))
>>> banana
'A yellow sickle shaped fruit'
>>> name
'banana'
>>> eval(name)
'A yellow sickle shaped fruit'
>>>

*ducks behind asbestos shelter to hide from the predicted flames *

But Seriously - I think eval is good for just this kind of purpose - does what
was wanted, namely creating the variable with the same name as the content of a
string... - its also useful to access a variable if you have been given its name
in a string, instead of being passed the thing itself - then you don't need the
compile bit...

Caveat Emptor

- Hendrik







More information about the Python-list mailing list