What is a "callable"?

Question:

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 ?

Asked By: e-satis

||

Answers:

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
>>> 

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.

Answered By: Joe Skora

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.

Answered By: easeout

A callable is anything that can be called.

The built-in 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
Answered By: Florian Bösch

__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)
Answered By: MvdD

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
Answered By: Armin Ronacher

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 and 3.1, use callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable).

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')
Answered By: jfs

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()

Answered By: Andrea Ambu

callables implement the __call__ special method so any object with such a method is callable.

Answered By: cobie

Let me explain backwards:

Consider this…

foo()

… as syntactic sugar for:

foo.__call__()

Where foo can be any object that responds to __call__. When I say any object, I mean it: built-in types, your own classes and their instances.

In the case of built-in types, when you write:

int('10')
unicode(10)

You’re essentially doing:

int.__call__('10')
unicode.__call__(10)

That’s also why you don’t have foo = new int in Python: you just make the class object return an instance of it on __call__. The way Python solves this is very elegant in my opinion.

Answered By: hcalves

To check function or method of class is callable or not that means we can call that function.

Class A:
    def __init__(self,val):
        self.val = val
    def bar(self):
        print "bar"

obj = A()      
callable(obj.bar)
True
callable(obj.__init___)
False
def foo(): return "s"
callable(foo)
True
callable(foo())
False
Answered By: Ravi Singh

Callable is a type or class of "Build-in function or Method" with a method
call

>>> type(callable)
<class 'builtin_function_or_method'>
>>>

Example:
print is a callable object. With a build-in function call
When you invoke the print function, Python creates an object of type print and invokes its method call passing the parameters if any.

>>> type(print)
<class 'builtin_function_or_method'>
>>> print.__call__(10)
10
>>> print(10)
10
>>>
Answered By: maris

A class, function, method and object which has __call__() are callable.

You can check if callable with callable() which returns True if callable and returns False if not callable as shown below:

class Class1:
    def __call__(self):
        print("__call__")

class Class2:
    pass

def func():
    pass

print(callable(Class1))   # Class1
print(callable(Class2))   # Class2

print(callable(Class1())) # Class1 object
print(callable(Class2())) # Class2 object

print(callable(func))     # func

Then, only Class2 object which doesn’t have __call__() is not callable returning False as shown below:

True  # Class1
True  # Class2
True  # Class1 object
False # Class2 object
True  # func

In addition, all of them below are not callable returning False as shown below:

print(callable("Hello"))  # "str" type
print(callable(100))      # "int" type
print(callable(100.23))   # "float" type
print(callable(100 + 2j)) # "complex" type
print(callable(True))     # "bool" type
print(callable(None))     # "NoneType"
print(callable([]))       # "list" type
print(callable(()))       # "tuple" type
print(callable({}))       # "dict" type
print(callable({""}))     # "set" type

Output:

False # "str" type
False # "int" type
False # "float" type
False # "complex" type
False # "bool" type
False # "NoneType"
False # "list" type
False # "tuple" type
False # "dict" type
False # "set" type
Answered By: Kai – Kazuya Ito
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.