[Python-ideas] Statically checking purity of functions
Christoph Groth
christoph at grothesque.org
Thu Jun 9 09:37:27 EDT 2016
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.
Even though Python is a very dynamic language, in practice many
routines (when called with arguments of the intended type) are
pure in the functional programming sense, i.e. they have no
observable side effects and the result reproducibly depends on the
arguments.
I think there could be many interesting applications of knowing
whether a function is pure or not. Example: Long-running
computations often need to be parallelized. There are plenty of
ways to parallelize Python code (think of concurrent.futures or
ipyparallel) and most of them make implicit assumptions that some
functions are pure.
Another example: if the purity of functions would be known,
Jupyter notebooks could automatically deduce the side effects of
code cells and thus calculate their dependencies on each
other. Changes to a cell could thus invalidate other (dependent)
cells.
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?
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/20160609/2d2e1283/attachment.sig>
More information about the Python-ideas
mailing list