views:

6471

answers:

11

Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.

I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.

Could you give me some explanations, including examples with the magic method ?

+1  A: 

A Callable is an object that has the __call__ method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).

Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.

[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 15:55:44) 
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'()    # <== Here we attempt to call a string.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
ConcernedOfTunbridgeWells
+1  A: 

Quite simply, a "callable" is something that can be called like a method. The built in function "callable()" will tell you whether something appears to be callable, as will checking for a call property. Functions are callable as are classes, class instances can be callable. See more about this here and here.

Joe Skora
A: 

It's something you can put "(args)" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.

Kevin Conner
+21  A: 

A callable is anything that can be called.

The buildin callable (PyCallable_Check in objects.c) checks if the argument is either:

  • an instance of a class with a __call__ method or
  • is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)

The method named __call__ is (according to the documentation)

Called when the instance is ``called'' as a function

Example

class Foo:
  def __call__(self):
    print 'called'

foo_instance = Foo()
foo_instance() #this is calling the __call__ method
Florian Bösch
Note that the builtin callable is being removed in Python 3.0 in favor of checking for __call__
Eli Courtwright
@Eli: Hmm that sounds like a **very** bad move. `callable` actually tells you if something is callable or not, while checking for `__call__` tells you nothing; If an object `o` provides `__getattribute__` or `__getattr__`, `hasattr(o, '__call__')` may return True, yet `o` will still not be callable because Python skips `__getattribute__` and `__getattr__` for calls. The only real way left to check if something is callable is thus EAFP.
Longpoke
+2  A: 

__call__ makes any object be callable as a function.

This example will output 8:

class Adder(object):
  def __init__(self, val):
    self.val = val

  def __call__(self, val):
    return self.val + val

func = Adder(5)
print func(3)
A: 

Guy, "callable is something than can be called" is not really a good definition, do you realize that ? It's like saying that a voting machine is a machine that allow you to vote, that does not add any value.

e-satis
Look up the link on Currying in my post above. Python does not make anything like as much use of this type of capability as (say) Ruby or Smalltalk - or indeed functional languages such as Haskell. Reading up a bit about Functional Programming should illuminate this a bit.
ConcernedOfTunbridgeWells
Thanks. I'll check that.
e-satis
A: 

In Python a callable is an object which type has a __call__ method:

>>> class Foo:
...  pass
... 
>>> class Bar(object):
...  pass
... 
>>> type(Foo).__call__(Foo)
<__main__.Foo instance at 0x711440>
>>> type(Bar).__call__(Bar)
<__main__.Bar object at 0x712110>
>>> def foo(bar):
...  return bar
... 
>>> type(foo).__call__(foo, 42)
42

As simple as that :)

This of course can be overloaded:

>>> class Foo(object):
...  def __call__(self):
...   return 42
... 
>>> f = Foo()
>>> f()
42
Armin Ronacher
+4  A: 

@Kevin Little: That is wrong. __call__ of the object type is called. And because it's a descriptor, it doesn't show up in dir():

>>> type(int).__call__(int)
0
>>> type(object).__call__(object)
<object object at 0x523460>
Armin Ronacher
I stand corrected -- dir() ain't telling the whole truth! Answer removed.
Kevin Little
+12  A: 

From Python's sources object.c:

/* Test whether an object can be called */

int
PyCallable_Check(PyObject *x)
{
    if (x == NULL)
     return 0;
    if (PyInstance_Check(x)) {
     PyObject *call = PyObject_GetAttrString(x, "__call__");
     if (call == NULL) {
      PyErr_Clear();
      return 0;
     }
     /* Could test recursively but don't, for fear of endless
        recursion if some joker sets self.__call__ = self */
     Py_DECREF(call);
     return 1;
    }
    else {
     return x->ob_type->tp_call != NULL;
    }
}

It says:

  1. If an object is an instance of some class then it is callable iff it has __call__ attribute.
  2. Else the object x is callable iff x->ob_type->tp_call != NULL

Desciption of tp_call field:

ternaryfunc tp_call An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call(). This field is inherited by subtypes.

You can always use built-in callable function to determine whether given object is callable or not; or better yet just call it and catch TypeError later. callable is removed in Python 3.0, use callable = lambda o: hasattr(o, '__call__')

Example, a simplistic cache implementation:

class Cached:
    def __init__(self, function):
        self.function = function
        self.cache = {}

    def __call__(self, *args):
        try: return self.cache[args]
        except KeyError:
            ret = self.cache[args] = self.function(*args)
            return ret

Usage:

@Cached
def ack(x, y):
    return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1)

Example from standard library, file site.py, definition of built-in exit() and quit() functions:

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
J.F. Sebastian
I find the example for the __call__ method highly missleading because it mixes it with a recipe for caching and decorators, which add nothing to the understanding of __call__
Florian Bösch
@Florian Bösch: It is a real-world example (I've just copy-pasted that code snippet, I didn't write it for the answer). I'm sorry you find it misleading.
J.F. Sebastian
J.F. Sebastian, an example is good if you can take nothing away anymore without breaking it. Direct your gaze a bit below to my answer to see an example that demonstrates nothing but __call__.
Florian Bösch
Florian Bösch
J.F. Sebastian
@J.F. Sebastian: It's BS that more life-like examples are better. I could show you life-like code that would make you weep as an example. Simple examples work too, and they work better to illustrate something because they don't distract.
Florian Bösch
+3  A: 

A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.

Every time you define a function python creates a callable object. In example, you could define the function func in these ways (it's the same):

class a(object):
    def __call__(self, *args):
        print 'Hello'

func = a()

# or ... 
def func(*args):
    print 'Hello'

You could use this method instead of methods like doit or run, I think it's just more clear to see obj() than obj.doit()

Andrea Ambu