Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "callable"?

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 ?

like image 329
e-satis Avatar asked Sep 21 '08 15:09

e-satis


People also ask

What are callable in Python?

In Python, a callable is a function-like object, meaning it's something that behaves like a function. Just like with a function, you can use parentheses to call a callable. Functions are callables in Python but classes are callables too!

What does callable mean in programming?

A callable object, in computer programming, is any object that can be called like a function.

What makes a function callable?

A callable object is an object which can be used and behaves like a function but might not be a function. By using the __call__ method it is possible to define classes in a way that the instances will be callable objects. The __call__ method is called, if the instance is called "like a function", i.e. using brackets.

What is a callable C++?

(C++11) [edit] A Callable type is a type for which the INVOKE operation (used by, e.g., std::function, std::bind, and std::thread::thread) is applicable. The INVOKE operation may be performed explicitly using the library function std::invoke.


2 Answers

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 
like image 185
Florian Bösch Avatar answered Oct 02 '22 19:10

Florian Bösch


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') 
like image 25
jfs Avatar answered Oct 02 '22 18:10

jfs