turning a string into an object name

A. Jones netzapper at magicstar.net
Thu Apr 4 13:10:58 EST 2002


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.

Furthermore, you can wrap it inside a class.

class test:
	def wrongHeaded(self, name, value):
	    exec "self."+name+'='+repr(value)
	    print vars()

this produces no exceptions, and doesn't cause any problems, since
vars is never defined... only self.vars is.

Netzapper/Aubrey Jones


-----------== Posted via Newsfeeds.Com, Uncensored Usenet News ==----------
   http://www.newsfeeds.com       The Largest Usenet Servers in the World!
------== Over 100,000 Newsgroups - Ulimited downloads - 19 servers ==-----



More information about the Python-list mailing list