module __call__

1 view
Skip to first unread message

Dirck Blaskey

unread,
Jun 25, 2001, 4:30:23 AM6/25/01
to
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
module.function()

you could:

import module
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)

=======================================
"""
modulecall.py

enable def __call__(): at module level

thanks to Alex Martelli (ale...@yahoo.com)

di...@danbala.com
"""

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 """
sys.modules[modulename]=_callable_module(modulename)

sys.modules[__name__]=_callable_module(__name__)
================================================
"""
test.py

test modulecall.py:

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

modulecall(__name__)

def __call__():
print "module __call__ test"

Reply all
Reply to author
Forward
0 new messages