Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are non-pure functions in python?

Tags:

python

As a definition, I learnt that,

non-pure functions have some input (their arguments) and return some output (the result of applying them) [...] and in addition [...] can also generate side effects, which make some change to the state of interpreter or computer.

(Paraphrased from Building Abstractions with Functions (PDF).)

For example: the print(2) function returns nothing (None) in addition as a side effect print function (not Python interpreter) itself prints the value.

In the above definition, I did not understand the meaning of 'changing the state of interpreter or computer'. What does that mean?

like image 903
overexchange Avatar asked Mar 29 '14 15:03

overexchange


2 Answers

Any function that affects any state other than that of local variables is a non-pure function.

Changing a global is non-pure, for example:

some_list = []

def foo(bar):
    some_list.append(bar)

foo('baz')

The function foo changed the state of some_list; it is thus non-pure. A pure version would be:

def foo(bar, lst):
    return lst + [bar]

some_list = []
now_list = foo('baz', some_list)

Here foo only affects state by taking the input arguments and producing an output value. The original some_list object was not mutated either, a new object was returned instead.

Pure functions also must produce outputs that depend only on the inputs; a function that produces input based on external state is not pure either. time.time() is not pure, it returns a value based on the state of a clock, which was not an input to the function.

like image 137
Martijn Pieters Avatar answered Oct 19 '22 11:10

Martijn Pieters


We call a function pure if it satisfies two important extra properties:

  1. Behaviour that is only influence by input.
    • Most usually fails if the function code relies on a variable in the main namespace that was not passed in as an argument (making it local).
  2. Influence on the rest of the program should only be via its output (return value).
like image 21
user10908639 Avatar answered Oct 19 '22 11:10

user10908639