Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to prevent side effects in python?

Is there any way to prevent side effects in python? For example, the following function has a side effect, is there any keyword or any other way to have the python complain about it?

def func_with_side_affect(a):
    a.append('foo')
like image 817
yigal Avatar asked Dec 13 '13 14:12

yigal


People also ask

How do I stop programming side effects?

One of the best ways to avoid side effects in our program is to use pure functions, remember when we were talking about the quality of a good function, we said a function must be pure to meet the requirements of a quality function.

Does Python have side effects?

A Python function is said to cause a side effect if it modifies its calling environment—for example, modifying an argument object.

What is meant by statement having a side effect in Python?

Function is said to have a side effect if it changes anything outside of its function definition like changing arguments passed to the function or changing a global variable.

What are side effects in code?

A side effect is when a function relies on, or modifies, something outside its parameters to do something. For example, a function which reads or writes from a variable outside its own arguments, a database, a file, or the console can be described as having side effects.


2 Answers

Python is really not set up to enforce prevention of side-effects. As some others have mentioned, you can try to deepcopy the data or use immutable types, but these still have corner cases that are tricky to catch, and it's just a ton more effort than it's worth.

Using a functional style in Python normally involves the programmer simply designing their functions to be functional. In other words, whenever you write a function, you write it in such a way that it doesn't mutate the arguments.

If you're calling someone else's function, then you have to make sure the data you are passing in either cannot be mutated, or you have to keep around a safe, untouched copy of the data yourself, that you keep away from that untrusted function.

like image 92
John Y Avatar answered Sep 30 '22 18:09

John Y


No, but with you example, you could use immutable types, and pass tuple as an a argument. Side effects can not affect immutable types, for example you can not append to tuple, you could only create other tuple by extending given.

UPD: But still, your function could change objects which is referenced by your immutable object (as it was pointed out in comments), write to files and do some other IO.

like image 21
Bunyk Avatar answered Sep 30 '22 19:09

Bunyk