Re: Can I use the getattr functionality in a module?

Guido.van.Rossum@cwi.nl
Mon, 20 Mar 1995 11:06:22 +0100

> While working on my python khoros interface a question came to me. I
> know how to use the getattr method while building a type within "C".
> I was wondering if I could do the same but from within the module
> interface itself. I would like to bind methods to my module
> on-the-fly. For example:
>
> If some one trys this:
>
> import khoros
>
> a = khoros.get("lenna.xv")
>
> q = khoros.kflip(a)
>
> I would like to be able to trap the call to kflip in my "C" code and
> query the khoros system to see if kflip is a valid method. This way I
> can interface to all of khoros and only bring into-the-interface often
> used methods, leaving seldom used methods to be dynamically bound.

You can't do that for ordinary modules, since their getattr() is fixed
and requires that the name is already defined in the dictionary.
However you can do it with object types you define yourself (and I
seem to understand that you are already doing that). I see two ways
of exploiting this for the khoros module:

- Instead of making these functions part of the module, add a magic
object to the module and make them methods of that object -- it can
then do the lazy import. Then tell your users to use methods of this
object.

- In the initialization of the module, manipulate sys.modules so that
sys.modules['khoros'] is not a module but a special object as in the
previous item (there may be a line in add_module that prevents this
from working -- I'm willing to take it out).

BTW, when you ask Khoros "does a function named kflip exist", does it
also tell you what the parameter types are? Or do all functions have
the same parameter list, or is there another way to tell?

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>