What are non-pure functions in 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?
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:
- 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).
- Influence on the rest of the program should only be via its output (return value).