According to Wikipedia, a function or expression is said to have a side effect if it modifies some state outside its local environment. Let’s understand this in depth by examples.
To understand side effects, first, we should know what “state” is. In layman terms, the state refers to the value of the variable at any given point in the program like x=2.
Now, the above Wikipedia definition might have started to make some sense. If not, don’t worry, see the figure below.
In this figure, we have a variable x that is outside the scope of two functions. Clearly, after the Function_2 call, the value of x changes which means that Function_2, other than returning value(if any), is interacting with variables outside its local environment and thus has a side effect.
In general, any lasting effect that occurs in a function, not through its return value, is called a side effect. Not through its return value means if we assign x=Function_1(), this will clearly change the value of x but this is not a side effect. For side effect, the change should occur inside a function.
Common ways to have side effects:
- Modifying a non-local variable: Let’s understand by an example
Python12345678910111213x=3def square(x):x=x*xreturn xdef square_side_effect():global xx=x*xreturn xprint(x) # 3print(square(x)) # 9print(x) # 3print(square_side_effect()) # 9print(x) # 9
The x in the square() function is local to its scope so no change in outside x. Global in square_side_effect() makes x global so any change in x will change it in whole code (outside function scope) so the square_side_effect function() is not pure(has side effects).
- Changing the value of a mutable object: Let’s take Lists which is a mutable object.
Python12345678lst = [1,2,'Pankaj']def list_side_effect(lst):lst = 1lst = 'Kang'return lstprint(lst) # [1,2,'Pankaj']list_side_effect(lst)print(lst) # [1,1,'Kang']
Clearly, after calling list_side_effect(), the value of lst changes so, list_side has side effects.
- Performing Input/Output operations: This doesn’t change any objects or variable value, but it does have a potential lasting effect outside the function call because a person might see the output and be influenced by it.
- Calling other side-effect functions
Now, you might have got some feeling about the side effects. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.