turning a string into an object name

Jeff Shannon jeff at ccvcorp.com
Thu Apr 4 16:00:26 EST 2002


In article <3cac943f.132176618 at mammoth.usenet-access.com>, 
netzapper at magicstar.net says...
> On Thu, 04 Apr 2002 11:56:24 GMT, Alex Martelli <aleax at aleax.it>
> wrote:
> 
> >You cannot use ANY identifier safely after that exec
> >statement, as you have no idea any more what the
> >identifier can refer to.  As a bonus, your code crawls,
> >since the Python compiler knows it does not know, and
> >therefore executes a full identifier look-up at runtime
> >rather than recognizing local variables at compile time.
> >
> >What kind of useful code can you write without being
> >able to use ANY identifier safely?  WHY would you ever
> >WANT to trample all over your namespace to ensure every
> >identifier becomes an utter and total mystery?  Beats me.
> 
> I agree with you if it's an arbitrary string being passed to your exec
> call .  However, if you have some idea of what the form of the string
> is going to be, it doesn't seem so dangerous.  For instance:
> 
> for x in range(0, 100):
> 	exec foo + `x` + " = " + "myClass()"
> 
> allows you to easily make a large list of sequentially named
> variables, with no chance of stepping on a system call.

And *why* on earth would you want to do that, instead of:

foo = [myClass() for x in range(100)]

which creates a *true* list of 100 objects, which are not just 
sequentially named, but are an actual sequence?  Surely it's not 
so much easier to write foo23 than to write foo[23] ... and of 
course, your method will require even *more* exec statements when 
you want to modify all 100 of these objects:

for x in range(100):
    exec foo + `x` + " = " + foo + `x` + " % 5"

compared to:

foo = [x % 5 for x in foo]

Creating sequentially-named variables is the *wrong* approach.  
If you have numerous objects that are conceptually similar, so 
that it makes sense to name them sequentially, then you *really* 
want to put them in a list or dictionary instead.

The same thing is true of almost *every* use of exec or eval() -- 
it seems handy, but if you look for it, there's a better solution 
to your real problem.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list