[Python-ideas] making a module callable

Terry Reedy tjreedy at udel.edu
Tue Nov 19 23:37:57 CET 2013


On 11/19/2013 4:39 PM, Haoyi Li wrote:

>     2013/11/19 Michael Foord
>     <fuzzyman at gmail.com
>     <mailto:fuzzyman at gmail.com>>
>
>         On 19 November 2013 18:09, Philipp A.
>         <flying-sheep at web.de
>         <mailto:flying-sheep at web.de>> wrote:
>
>             imho it would simplify the situation. currently, everything
>             is callable that has a |__call__| property which is itself
>             callable:
>
>         This is why module objects are not callable even if they have a
>         __call__. They are *instances* of ModuleType and the __call__
>         method is looked up on their type, not the instance itself. So
>         modules not being callable even when they a __call__ is not an
>         anomaly, even if it is not convenient sometimes.

In order to make modules callable, ModuleType must have a __call__ 
method. In order to make the call execute code in the module,  that 
method should delegate to a callable in the module instance that has a 
known special name, such as __main__.

class ModuleType():
   def __call__(self, *args, **kwds):
     return self.__main__(*args, **kwds)

Doc: "The __main__ object of a module is its main callable, the one that 
is called if the module is called without specifying anything else.

If this were done...

 > Someone
 > >there are some modules who just have one single main use (pprint)
 > > and  could profit from that.

 > pprint.pprint()

then adding

   __main__ = pprint

to pprint should make the following work:

   import pprint; pprint(ob)

 > time.time()
 > random.random()
 > copy.copy()
 > md5.md5()
 > timeit.timeit()
 > glob.glob()
 > cStringIO.cStringIO()
 > StringIO.StringIO()

etc

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list