Tom Granot-Scalosub Tom Granot-Scalosub - 2 months ago 7
Python Question

Python lambda function "translation" causes recursion error

While attempting to understand python lambda functions, I "translated" this function:

s = lambda y: y ** y; s(3)


Into this regular, defined function:

def power_of_self(y):
return y ** y
power_of_self(3)


When I tried running it as a script (
python lambda_stuff.py
) I had no problem. However, when attempting to run it via the Python shell, this weird thing happened:

>>> def power_of_self(y):
... return y ** y
... power_of_self(3)
File "<stdin>", line 3
power_of_self(3)
^
SyntaxError: invalid syntax
>>> print power_of_self(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
**A FEW HUNDRED MORE OF THESE**
RuntimeError: maximum recursion depth exceeded


Why did my script execution differ from my shell execution? I wonder if the
...
had anything to do with it.

Answer

The ... means the python shell was waiting for more statements as part of the function. You need a blank line to end the function when entering an indented block from directly into the python shell.

>>> def power_of_self(y):
...     return y ** y
...
>>> power_of_self(3)
27