[Python-ideas] Statically checking purity of functions

Paul Moore p.f.moore at gmail.com
Thu Jun 9 10:14:49 EDT 2016


On 9 June 2016 at 14:37, Christoph Groth <christoph at grothesque.org> wrote:
> With plain Python (without type annotations) there is no way to verify the
> purity of a function as has been well explained here:
> http://stackoverflow.com/a/31664102
>
> 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?

That sounds both reasonable and potentially useful, albeit of
relatively niche interest. It's quite similar to Perl's "taint checks"
that track whether data is affected by external input (although the
latter marks *data*, not functions).

I've not looked into mypy yet, so all I know about it is from skimming
some of the typing discussions here. But if it's possible to write a
plugin for mypy to do something like this, that would be pretty
awesome.

I'm not sure how much a capability like that would affect Python
itself, though. (In fact, I'd say it ought not to - being able to do
something like this without any changes to the language would be
ideal).

Paul


More information about the Python-ideas mailing list