[Python-ideas] making a module callable

Michael Foord fuzzyman at gmail.com
Tue Nov 19 19:19:38 CET 2013


On 19 November 2013 18:09, Philipp A. <flying-sheep at web.de> wrote:

> 2013/11/19 Gregory P. Smith <greg at krypto.org>
>
> While I don't ordinarily endorse this use case it'd be nice not to require
>> hacks involving sys.modules monkeying such ashttps://github.com/has207/flexmock/pull/89to make a module callable.
>>
>> This obviously touches on the larger ideas of what is a module vs a class
>> and why are they different given that they're "just" namespaces.
>>
>  hmm, interesting thought. there are some modules who just have one
> single main use (pprint) and could profit from that.
>
> imho it would simplify the situation. currently, everything is callable
> that has a __call__ property which is itself callable:
>
Not quite true:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo: pass
...
>>> f = Foo()
>>> f.__call__ = lambda *args: 3
>>>
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Foo' object is not 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.

Michael





> class Foo():
>     __call__(self):
>         pass
>     def bar():
>         pass
>
> foo = Foo()
> foo()
> foo.bar()
> def baz():
>     pass
>
> foo.baz = baz
> foo.baz()
>
> except modules. which feels is imho like an artificial limitation.
>
> – phil
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
>
>


-- 

http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131119/ec9a449d/attachment.html>


More information about the Python-ideas mailing list