module with __call__ defined is not callable?

Paul Rubin http
Thu Feb 9 05:31:29 EST 2006


Steve Holden <steve at holdenweb.com> writes:
> Right. While we're at it, why don't we make strings callable. Calling
> a string could call the function whose name (in some namespace or
> other) was in the string. 

Making a string subclass callable works fine:

    >>> class f(str):
    ...   def __call__(self): print len(self)
    ...
    >>> z=f('foo')
    >>> z
    'foo'
    >>> z()
    3
    >>>

> Why should a module be callable? What's the advantage? 

I've wanted to be able to say

   import frotz
   x = frotz(23)

instead of having to say "from frotz import frotz" or "x = frotz.frotz(23)".

That kind of cruft pervades code that uses the standard library and
callable modules could clean a lot of it up.  No more random.random,
sha.new, etc.  Just call the module to make an instance of the class
it defines.

> Should we be able to add two modules together, yielding a module
> that contains all the code of both modules? What happens if I
> multiply a module by two - presumably the result should be the same
> as adding a module to itself?  Perhaps we should be able to divide a
> module by a function?

There should be no built-in definitions of those operations but 
if you're a duck-typing believer, it's clear what __add__ etc. should do.



More information about the Python-list mailing list