5

Here is what I am working with so far

def f(n):
    return n

f.__call__ = lambda n: n + 1

print f(2) #I expect an output of 3 but get an output of 2

I am not interested in another way to achieve the desired output. Rather, for educational purposes, I would like to know why overriding the __call__ as I have done, doesn't work as I expect.

John
  • 13,197
  • 7
  • 51
  • 101

1 Answers1

5

This appears to be due to special-casing of function types in ceval.c, in call_function:

if (PyFunction_Check(func))
    x = fast_function(func, pp_stack, n, na, nk);
else
    x = do_call(func, pp_stack, na, nk);

I'd guess that this is probably for efficiency, since calling regular functions, and ignoring the __call__ attribute, is by far the most common kind of calling that gets done.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
Owen
  • 38,836
  • 14
  • 95
  • 125
  • I've changed the link to point to hg.python.org since this is the official repository for CPython now. – unutbu Aug 13 '13 at 02:46