[Tutor] Working with files, Truckers log

Jeff Shannon jeff@ccvcorp.com
Mon, 08 Apr 2002 11:32:35 -0700


Alexandre Ratti wrote:

> Hello Jeff,
>
>
> >Why on earth should eval() be used for this, when there's perfectly good
> >conversion functions??
> [...]

> >There really is almost never a reason to use eval().  Really.  :)
>
> How about this kind of use:
>
> def factoryFromName(className, *args):
>      "className is a string."
>      return eval(className)(*args)
>
> Admittedly, I can't think up any reason to use this code in a real app
> right now :-)

Well, in this sort of case, I'd probably pass in a class object, instead of a
classname string.  But, if I *had* to get the object from a name string, I'd
probably use getattr() on the module -- I'd expect the class to be defined in some
other module, and just do this:

def FactoryFromName(module, classname, *args):
    return getattr(module, classname)(*args)

Or, if the class was defined in the current module:

def FactoryFromName(classname, *args):
    import ThisModule
    return getattr(ThisModule, classname)(*args)

(Yes, it *is* legal to import the current module from within a function like this.
You can't do it at the top level -- if this import code executes while the module
is first being imported, you'll end up with an endless recursion.  But once the
module is imported elsewhere, you can execute this function to get access to the
current module's namespace.)

Jeff Shannon
Technician/Programmer
Credit International