turning a string into an object name

Alex Martelli aleax at aleax.it
Thu Apr 4 13:53:08 EST 2002


A. Jones wrote:
        ...
> Furthermore, you can wrap it inside a class.

But then there's no need for the horrors of exec and you can do it MUCH
more cleanly and safely, to wit:

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

class test:
    def rightHeaded(self, name, value):
        setattr(self, name, value)

You can print vars(self) too, if you want.  But the point is that setattr
is perfectly clean and safe, well-performing, specific and restricted in
its semantics -- all the good things that exec is not.

But of course you can't use setattr to create *VARIABLES* -- only
*ATTRIBUTES* of some object (you could use it on a module to make
"global variables" for that module, but that would not be quite as safe
and advisable as using it on an instance object).

It's exactly because it's so convenient to use (e.g.) attributes of an
instance, rather than variables, for such purposes, that it's unjustifiably
gauche to abuse exec in such wise.


Alex




More information about the Python-list mailing list