Search code examples
pythonfunctional-programmingtemporary

temporary variables in a python expression


Some (many? all?) functional programming languages like StandardML and Haskell have a type of expression in the form let ... in ... where is possible to create temporary variables with the scope of the expression itself.

Example: let a=b*c in a*(a+1)

It seems that in Python there is no expression construct similar to this.

Motivation:

For example the body of a lambda function must be a (one) expression. Not two expressions. Not a statement (an assignment is a statement and not an expression).

Moreover, when writing functional expressions and in general one-liners in python, things can become messy pretty easily (see my answer to Python 2 list comprehension and eval).

The point of such a construct is to avoid repetition (which sometimes leads to re-computation), for example l[:l.index(a)]+l[l.index(a)+1:] instead of an hypothetic let i=l.index(a) in l[:i]+l[i+1:]


How can we achieve a similar language feature in python2 / python3?


Solution

  • This isn't really idiomatic code, but for single expressions you can use lambdas that you immediately invoke. Your example would look like this:

    >>> b, c = 2, 3
    >>> (lambda a: a * (a + 1))(b * c)
    42
    

    You can also write this using keyword arguments if that helps readability:

    >>> (lambda a: a * (a + 1))(a=b * c)
    42