turning a string into an object name
Chris Liechti
cliechti at gmx.net
Thu Apr 4 14:51:30 EST 2002
netzapper at magicstar.net (A. Jones) wrote in
news:3cac943f.132176618 at mammoth.usenet-access.com:
> 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.
until someone has the idea to pass some fancier names like
t.wrongHeaded('a; del None', 57)
and then have fun watching your entire program fail...
when you wrap it in a class there is no reason to not use getattr/setattr.
exec/eval is always critical like os.system() and the like. security holes
due to unmotivated eval/os.system etc. use come up every now and then and
you wound't want to be the author of that software.
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list