[Python-ideas] Statically checking purity of functions

Robert Collins robertc at robertcollins.net
Thu Jun 9 15:48:27 EDT 2016


On 10 June 2016 at 01:37, Christoph Groth <christoph at grothesque.org> wrote:
> Hello,
>
> As far as I can tell the following has not been discussed yet on the
> searchable internet.  It may seem that my idea concerns only mypy, but since
> "typing" is part of the stdlib, I believe it is appropriate for this mailing
> list.
>...
> But couldn't this be done with a static type checker like mypy? If mypy
> would track functions as pure or not pure, it should be able to verify the
> claimed purity of any new function.  For example, the following function
> would pass the test,
>
> @pure
> def add(a: int, b: int) -> int:
>   return a + b
>
> while the next one would produce an error
>
> @pure
> def add_random(a: int) -> int:
>   return a + random.randrange(10)
>
> because the static checker would know that random.randrange() is not pure
> (it modifies the state of the random module).
>
> Am I overseeing any problems with the above?

The problem, as Cory demonstrates, is that purity is transitive: you
have to know that all the runtime interactions are also pure, or your
function stops being pure.

external names like random in add_random can never be pure (because
any piece of impure code can change the module globals to rebind
random to something else). This means that any pure function would
have to accept as parameters everything it operates on, and you'd need
to error on any call to a pure function with impure arguments. It
would be an interesting exercise to see how it plays out in practice
though.

-Rob


More information about the Python-ideas mailing list