6

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 ?

Alex Brooks
  • 5,133
  • 4
  • 21
  • 27

1 Answers1

11

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.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • What you *can* do is check if `f` is pure **assuming** `type(x) == int`. Because Python is dynamically typed, you would have to add type annotations manually, though. – Jasmijn May 09 '12 at 07:31