[Tutor] python $i equivalent ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jun 10 16:56:56 EDT 2004



On Thu, 10 Jun 2004, Paul Worrall wrote:

> On Wednesday 09 Jun 2004 22:25, Michele Alzetta wrote:
> > Suppose I wanted to create numerous instances of a class
> > and name each istance according to an element in a list ?
> >
> > for element in list:
> >     element = Class()
> >
> > doesn't work of course; I need something like the bash '$'
> > stuff here
> >
> > for element in list:
> >     $element = Class()
> >
> > (of course this is neither bash nor python, I know !)
> >
> > How would this be done ?
>
> Does this do what you want?
>
> for element in list:
>     exec element + " = Class()"
>
> this compiles a Python statement as a string and passes it to the exec
> built-in function for execution.  list should contain only strings.


Hi Paul,

Exec/eval, in this case, has a few points against it.  One is that, from a
readability standpoint, it's not so nice for people.  Let's look at the
code again:

###
for element in list:
    exec element + " = Class()"
###

It's not immediately clear what new variable names are being introduced
without looking at the content of 'list'.  If the content of 'list' is
from a file, then there's no way to know up front what variables are
coming in.


It's also unsafe --- as Don Arnold mentioned earlier in the thread:

> And you can use any legal dictionary key as a variable name, without its
> having to be a valid Python identifier:
>
> >>> myvars['not~a~legal~name'] = 42
> >>> print myvars['not~a~legal~name']
> 42


In particular, there are a few reserved "keywords" that aren't allowed as
Python variable names.  Things like 'pass', for example, can't be used as
variable names, but they could be perfectly legitimate elements in
Michele's list.

So the code:

###
for element in list:
    exec element + " = Class()"
###

might work or might not work, depending on the content of the 'list'.  We
could easily get SyntaxError from the code above.


(There's also the huge security risk of exec/eval which we can talk about
later... *grin*)


The dictionary approach:

###
myvars = {}
for element in list:
    myvars[element] = Class()
###

dodges these problems, which is why it's the approach that we'll push
hard.


Hope this helps!




More information about the Tutor mailing list