[Python-ideas] Statically checking purity of functions

Cory Benfield cory at lukasa.co.uk
Thu Jun 9 10:22:29 EDT 2016


> On 9 Jun 2016, at 14:37, Christoph Groth <christoph at grothesque.org> wrote:
> 
> 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

Here’s where this falls down (NB, the print is just a simple example of non-purity, but you can imagine that you can just do arbitrary code).

class SideEffectyInt(int):
    def __add__(self, other):
        if other == 3:
            print(“YAY")
        return super().__add__(other)

This SideEffectyInt() object is suitable for passing into your pure “add” function, but has an impure add logic. I’m not sure how mypy could resolve this problem: I presume it’d need purity declarations for every possible function on every type *and* the ability to see all function invocations, which is pretty difficult given that Python’s dynamism makes it possible to invoke arbitrary functions.

So I don’t really see how this pure decorator could *enforce* purity.

Cory
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160609/65cbb55d/attachment.sig>


More information about the Python-ideas mailing list