temporary variables in a python expression

2.7k views Asked by At

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?

2

There are 2 answers

0
Ismail Badawi On BEST ANSWER

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
0
TigerhawkT3 On

You can sort of simulate a smaller scope for your temporary variable by putting it into an iterable and then looping over that iterable:

>>> b,c = 2,3
>>> var = [a*(a+1) for a in [b*c]][0]
>>> var
42

This puts the single value b*c into a list, then loops over that list in a comprehension, with each new value consisting of some transformation of each element. The created list is one element in length, and we get the first element in it with [0]. Without the comprehension, it looks as follows:

>>> b,c = 2,3
>>> var = []
>>> for a in [b*c]:
...     var.append(a*(a+1))
...
>>> var = var[0]
>>> var
42