Using exec

Alex Martelli aleax at aleax.it
Wed Aug 29 09:48:57 EDT 2001


"Kerim Borchaev" <warkid at storm.ru> wrote in message
news:mailman.999087493.19688.python-list at python.org...
> I need to reference an object's method given a string representation
> of it's name. Now I do it like this:
>
> exec( "c."+MethonName+"()" )

Use:
    getattr(c,MethonName)()

> or if I need to create an instance of class named ClassName I do this:
>
> exec( "inst="+ClassName+"()" )

This, of course, is totally different - you have an unqualified
name (and don't even know if it's a local or global name...?)
rather than the name of an attribute.

If you knew the name was global,
    inst = globals()[ClassName]()
would work; if you knew the name was local,
    inst = locals()[ClassName]()
would be OK.  But if you don't, it's rather a bother to try
both, as in:
    try: classobj = locals()[ClassName]
    except KeyError: classobj = globals()[ClassName]
    inst = classobj()
so it's understandable that one would take a shortcut:
    inst = eval(ClassName)()

However, the real underying question is, *WHY* do you have
to deal with the bother of recovering the class object (to
be called) from the classname -- why isn't the class object
itself passed instead of its name in the first place?  Using
object references directly is SO much handier & faster!


> but it seems ugly to me.

I fully agree -- it's downright ugly.  exec is particularly
horrible -- good thing eval exists, because it's far more
often needed than exec.  But by far most often one needs
neither, just by being careful to focus on the objects (the
real things) rather than their names (a transient accident).


Alex






More information about the Python-list mailing list