module __call__

Dirck Blaskey dirck at
Mon Jun 25 10:30:23 CEST 2001

last April I had posted:
> ...Gee-Wouldn't-It-Be-Nice-If...
> modules could def __call__():
> so you could call a module

It seemed to me like it sort of fit, and would
be useful for modules with a very simple interface,
so instead of:

  import module

you could:

  import module

Anyway, I would like to thank Alex Martelli for recently posting
a clue (for the clueless like myself) (in the thread on const), that
makes this possible.  Here's the code:  (let me know if I screwed it up)

    enable def __call__(): at module level
    thanks to Alex Martelli (aleaxit at

    dirck at    

import sys

class _callable_module:
    def __init__(self, name):
        m = sys.modules[name]
        self.__dict__['_module'] = m
        self.__dict__['_mdict'] = m.__dict__

    def __setattr__(self, name, value):
        self._mdict[name] = value
    def __getattr__(self, name):
        return self._mdict[name]
    def __call__(self, *pargs, **kargs):
        """ apply pseudo-module call """
        apply(self._module.__call__, pargs, kargs)

# make this module callable as a simple interface

def __call__(modulename):
    """ module call """


Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import test
>>> test()
module __call__ test
import modulecall


def __call__():
    print "module __call__ test"

More information about the Python-list mailing list