def f(x): return x f = lambda : f(5) f() => Traceback (most recent call last): File "<input>", line 1, in <module> File "<input>", line 4, in <lambda> TypeError: <lambda>() takes 0 positional arguments but 1 was given
I can see intuitively why this doesn’t work…it’s sort of a circular reference. Specifically what rule in Python is it breaking?
Advertisement
Answer
In addition to what @U12-Forward posted, the reason you create a circular reference is the late binding of the lambda. By the time it calls f(5)
it’s already referring to itself.
If your intent is to call your original f()
you can force the binding with:
f = lambda f=f: f(5)
and calling f()
will return 5
because that’s what the original f()
does.