Callable modules?

Fernando Perez fperez528 at yahoo.com
Wed Jul 24 20:12:46 EDT 2002


holger krekel wrote:

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

What about:

#somemodule.py
def filter1(self,args):
  ...

def filter2(self,args):
  ...

...

class someclass:
  ...

someclass.filter1 = filter1
someclass.filter2 = filter2
...

# end somemodule.py

I know there's still one little layer of redundant typing, but it only has to 
be done in the module which defines your class, not by the users. So you do 
it once and you are done.

Is there any reason why this doesn't address your requirements (I may well be 
missing something)?

cheers,

f.

ps. I guess you lose safety checks on what 'self' is when you invoke them as 
standalones, but you could always put an assertion in them if that is 
critically important.



More information about the Python-list mailing list