[Tutor] Working with files, Truckers log

Alexandre Ratti alex@gabuzomeu.net
Tue, 09 Apr 2002 11:12:49 +0200


Hello,


At 23:40 08/04/2002 -0400, you wrote:
>Date: Mon, 08 Apr 2002 11:32:35 -0700
>From: "Jeff Shannon" <jeff@ccvcorp.com>
>Subject: Re: [Tutor] Working with files, Truckers log

> > How about this kind of use:
> >
> > def factoryFromName(className, *args):
> >      "className is a string."
> >      return eval(className)(*args)

>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)

OK, thanks.

>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.)

That's interesting. Now, "ThisModule" is the module name. How can we avoid 
hard-coding it in the function? Is is possible to retrieve the name of the 
module the function object is defined in?

Also, how can you refer to "me" in a function? For a class instance, it's 
self. Is there a similar solution for a function object?


Cheers.

Alexandre