Define a function as a list item
Python def not flexible enough to handle common lvalues, such as list[0] . The language only allows you to use the identifier as the name of the function. Here are the relevant parts of the grammar rule for def-statement :
funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite funcname ::= identifier Instead, you can use a series of assignment and definition operators:
s = [None] def f(x, y): return x + y s[0] = f Alternatively, you can also save the lambda expression directly in the list:
s = [lambda x,y : x+y] Enabling this freedom will make parsing more complex ... for example, an expression in parentheses
...(x, y, z=3) can be either a parameter declaration (where 3 is the default value for the keyword parameter z) or a call (which passes the value of the keyword parameter z as 3 ).
If you want to allow the general assignment in def , you also need to allow
def foo(x, y, z=3)[3](x, y, z=3): ... where the first bracketed part has different semantic meanings and syntax rules from the second part.
Writing a parser for this is annoying (mainly because you need to process an arbitrary unlimited amount of source code without understanding it), and this is what, for example, leads to the worst parsing rule in the whole universe that I know (this is the scary most unpleasant parsing in C ++), which basically just gave up trying to get a decent language, abandoning ambiguity.
Note that in many cases where it is more difficult for a program to parse this because of ambiguity, it is even more difficult for a person to understand.
Python correctly evaluates readability as very important.
Functions in Python are, however, first-class objects, so you can easily solve your problem:
def foo(...): ... mylist[index] = foo or, only if the function is a single expression, with
mylist[index] = lambda ... : ... (but lambda very limited because it βhatesβ the Python community, and also because it will create some annoyance at the syntax level due to the need to handle indentation inside parentheses).
Also note that some Python newbies do not know that you can use def even inside a function; eg:
def register_http(): def handle_http(connection): ... global_register['http'] = handle_http which will designate the function as an element of the global map without polluting the global (modular) namespace with its name. A local def can also create a closure by capturing local state variables (read-only in 2.x or even read / write in 3.x).
Please also note that if you need some processing of a function, decorators may be useful. For example, defining
def register(name): def do_registering(f): global_register[name] = f return f return do_registering you can just use
@register('http') def handle_http(connection): ...