Guidelines for creating referentially transparent callables
Posted
by
max
on Programmers
See other posts from Programmers
or by max
Published on 2012-10-13T13:23:28Z
Indexed on
2012/10/13
15:53 UTC
Read the original article
Hit count: 210
python
|functional-programming
In some cases, I want to use referentially transparent callables while coding in Python. My goals are to help with handling concurrency, memoization, unit testing, and verification of code correctness.
I want to write down clear rules for myself and other developers to follow that would ensure referential transparency. I don't mind that Python won't enforce any rules - we trust ourselves to follow them. Note that we never modify functions or methods in place (i.e., by hacking into the bytecode).
Would the following make sense?
A callable object
c
of classC
will be referentially transparent if:
Whenever the returned value of
c(...)
depends on any instance attributes, global variables, or disk files, such attributes, variables, and files must not change for the duration of the program execution; the only exception is that instance attributes may be changed during instance initialization.When
c(...)
is executed, no modifications to the program state occur that may affect the behavior of any object accessed through its "public interface" (as defined by us).
If we don't put any restrictions on what "public interface" includes, then rule #2 becomes:
When
c(...)
is executed, no objects are modified that are visible outside the scope ofc.__call__
.
Note: I unsuccessfully tried to ask this question on SO, but I'm hoping it's more appropriate to this site.
© Programmers or respective owner