python newbie

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 3 16:58:49 CET 2007

Paul Rubin <> wrote:

> Duncan Booth <duncan.booth at invalid.invalid> writes:
>> modules are not special in any way, except that you cannot subclass
>> them. Oops, sorry I got that wrong. Modules are not special in any
>> way, they can have methods as well as functions:
> I've felt for a long time that you should be able to define __call__
> on a module, but that doesn't seem to be allowed, at least if you
> try it in the obvious way.

This isn't perfect (global variables have to be set before hooking the 
module) but it sort of works:

--------- ---------------
"""How to define a callable module"""
import sys, new
class CallableModule(new.module):
	def __call__(self, *args, **kw):
		self._call_(*args, **kw)

def _call_(*args, **kw):
    """A call method"""
    print "Called with %r args, %r kw" % (args, kw)

self = CallableModule(__name__, __doc__)
sys.modules[__name__] = self


>>> import callable
>>> callable('test')
Called with ('test',) args, {} kw
>>> callable
<module 'callable' from ''>

More information about the Python-list mailing list