[Python-ideas] making a module callable

Mathias Panzenböck grosser.meister.morti at gmx.net
Tue Nov 19 23:05:48 CET 2013


Maybe the solution would be to make it possible to "return" something else than a module object, similar to how node.js 
does it?

In node.js:

callme.js:
module.exports = function (a) { console.log("a:",a); };

 > require("./callme.js")("b")
a: b
undefined
 >

Possible way to do it in Python *already*:

callme.py:
import sys
sys.modules[__name__] = lambda a: print("a:",a)

 >>> import callme
 >>> callme('b')
a: b
 >>>


Maybe not very nice, but is there a reason why not to do this (except for it's ugliness)?


On 11/19/2013 10:39 PM, Haoyi Li wrote:
>  > there are some modules who just have one single main use (pprint) and could profit from that.
>
> A milion times this!
>
> pprint.pprint()
> time.time()
> random.random()
> copy.copy()
> md5.md5()
> timeit.timeit()
> glob.glob()
> cStringIO.cStringIO()
> StringIO.StringIO()
>
>
>
> On Tue, Nov 19, 2013 at 1:01 PM, Philipp A. <flying-sheep at web.de <mailto:flying-sheep at web.de>> 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.
>
>     you’re right, apologies. so the hack consists of switching a module’s class during runtime…
>
>     there’s also another hack, calldules <https://pypi.python.org/pypi/calldules>, making that automatic (funnily via
>     implicits effects when doing |import calldules|). note that it isn’t serious! just a programming exercise.
>
>
>     _______________________________________________
>     Python-ideas mailing list
>     Python-ideas at python.org <mailto:Python-ideas at python.org>
>     https://mail.python.org/mailman/listinfo/python-ideas
>
>
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list