There is no infinite loop because the __call__ method is __call__ actually called ("called") for all of these situations. It is called directly when there is a functional call to the object that the __call__ method __call__ .
Creating an instance of the normal class Cls(...) and a regular function call f() are known cases that are handled directly. Usually there is no actual call to __call__() , so there are a finite number of calls to the __call__ method that may ever occur, even in complex cases with deep inheritance, metaclasses, etc.
Since there has been some debate as to whether the conceptual infinite loops really short circuit, let's look at the parsed bytecode. Consider the following code:
def f(x): return x + 1 class Adder(object): def something(self, x): return x + 19 def __call__(self, x): return x + 1 def lotsacalls(y): u = f(1) a = Adder() z = u + a.something(y) return a(z * 10)
Sorry, this is a bit complicated, because I want to show several instances of a short circuit - namely, the usual def functions, __init__ calls, ordinary methods and __call__ special methods. Now:

So, here is the range of times that if Python really were, really “walking the tree” of the conceptual __call__ invocations, it should reference the Function classes (and possibly the Method ) and call them __call__ ). This is not true. It uses a simple bytecode CALL_FUNCTION in all cases, a short circuit of the conceptual tree transition. Logically, you can imagine that there is a Function class that has a __call__ method that is called when a function is called (i.e., an instance of the Function class). But actually it is not. The compiler, bytecode interpreter, and other parts of the foundations of the C-language do not actually walk metaclass trees. They short out like crazy.
Jonathan eunice
source share