What are non-pure functions in python?

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.


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).

Tags:

Python