Callable modules?
holger krekel
pyth at devel.trillke.net
Tue Jul 23 04:47:10 EDT 2002
Paul Rubin wrote:
> martin at v.loewis.de (Martin v. Loewis) writes:
> > You can put a callable object in sys.modules. Module objects
> > themselves are not callable.
>
> Is this documented somewhere? I don't see it in the obvious places.
>
> > > If there's not a way to do this already, maybe it's a reasonable
> > > addition.
> >
> > Maybe not. Why do you need this?
>
> Just to not have to say "foo.foo()" or "from foo import foo".
>
> If the main purpose of the module is to provide one function, I think
> it's cleaner to be able to import the module and call the function
> without special tricks.
Moreover, I often thought about integrating class and module types.
I am not primarly concerned about making modules callable, although
i might appreciate it.
My use case is
from somemodule.someclass import filter1
where 'filter1' would reference an unbound class-method.
I need this for implementing a class which offers filter
functions which can be applied either as
obj.filter1(args)
or
filter1(obj, args)
Of course, you can express the latter via
someclass.filter1(obj, args)
but i want to have filter1 (and 41 other filter methods)
potentially directly in the namespace. I *know* that i can write
filter1=someclass.filter1
filter2=someclass.filter2
...
but it's redundant and you have to repeat this scheme whereever
you use 'somemodule'. That's ugly where in fact i just want to say
from somemodule.filters import filter1,filter2, filter37
and someclass could inherit from 'filters', thus providing both
invocation methods. I know that i can *hack* this to work by
- doing new.module('somemodule.filters') in somemodule
and adding the modules functions at runtime to someclass.
- making up a package (with filters beeing in a different file)
and adding the modules functions at runtime to someclass
- some variant of this schema
but actually, doing the above 'from ....someclass import filter1,...'
seems much more expressive and doesn't involve any run-time hacks.
I hope i made my point clear enough. Basically i'd like to
generalize the namespace-injection methods 'import' and 'from'.
This might involves extending the Module-type to work
more like a "usual" class with __getattr__ and such. Probabally
it only involves extending the import machinery.
Unfortunately, i haven't found time to investigate the matter
but maybe someone can point out that it's the path to
all evil (read: wrong concept), anyway :-)
slightly?-off-topic-ly yours,
holger
More information about the Python-list
mailing list