Pure Functions

A pure function does not produce side effects. It communicates with the calling program only through parameters (which it does not modify) and a return value. Here is the doubleStuff function from the previous section written as a pure function. To use the pure function version of double_stuff to modify things, you would assign the return value back to things.


 
1
def doubleStuff(a_list):
2
    """ Return a new list in which contains doubles of the elements in a_list. """
3
    new_list = []
4
    for value in a_list:
5
        new_elem = 2 * value
6
        new_list.append(new_elem)
7
    return new_list
8
9
things = [2, 5, 9]
10
print(things)
11
things = doubleStuff(things)
12
print(things)
13


(ch09_mod2)

Once again, codelens helps us to see the actual references and objects as they are passed and returned.

1def doubleStuff(a_list):
2    """ Return a new list in which contains doubles of the elements in a_list. """
3    new_list = []
4    for value in a_list:
5        new_elem = 2 * value
6        new_list.append(new_elem)
7    return new_list
8
9things = [2, 5, 9]
10things = doubleStuff(things)
Krok 1 na 17
linia, która właśnie się wykonała

następna linia do wykonania

Wizualizacja kodu oparta o: Online Python Tutor
Ramki
Obiekty

(ch09_mod3)

Następna część - Which is Better?