Guidelines for creating referentially transparent callables
- by max
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 class C 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 of c.__call__.
Note: I unsuccessfully tried to ask this question on SO, but I'm hoping it's more appropriate to this site.