[Python-ideas] Statically checking purity of functions

Christoph Groth christoph at grothesque.org
Fri Jun 10 06:57:34 EDT 2016


Robert Collins wrote:

> 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).

True, but when checking for type correctness one faces exactly the 
same problem.  Consider the following script.  Uncommenting any of 
the commented-out blocks will make it fail in the same way, but 
mypy will only detect the first failure.

That's already not bad at all, since most of such renaming of 
global variables will typically happen at global scope. 
Sufficiently insidious monkey-patching can never be detected by a 
linter that only looks at the Python source. (Hey, it could happen 
inside a C extension module!)

import math

def bad_sin(x: float) -> str:
    return str(x)

### Mypy will detect this as a problem:
# math.sin = bad_sin

### Mypy will not mind the following:
# def do_evil():
#     math.sin = bad_sin
# do_evil()

def sin_squared(x: float) -> float:
    return math.sin(x)**2

print(sin_squared(math.pi / 6))

> 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.

You mean because one can never be sure about the purity of global 
variables?  That's true, but exactly to the same extent that one 
cannot be sure about the typing annotations of global variables.

I believe that such "weak" checking for purity would still be 
useful, just as the equally weak verification of typing by mypy is 
useful.

Christoph
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 818 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160610/4c6fe6c9/attachment.sig>


More information about the Python-ideas mailing list