Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing side effects in python

Is there a tool that enables you to annotate functions/methods as "pure" and then analyzes the code to test if said functions/methods are side effect free ?

like image 518
Alex Brooks Avatar asked May 09 '12 04:05

Alex Brooks


1 Answers

In the Python world, the question doesn't make much sense since objects have so much say in what happens in a function call.

For example, how could you tell if the following function is pure?

def f(x):
   return x + 1

The answer depends on what x is:

>>> class A(int):
        def __add__(self, other):
            global s
            s += 1
            return int.__add__(self, other)

>>> def f(x):
        return x + 1

>>> s = 0
>>> f(A(1))
2
>>> s
1

Though the function f looks pure, the add operation on x has the side-effect of incrementing s.

like image 112
Raymond Hettinger Avatar answered Oct 02 '22 06:10

Raymond Hettinger