[Python-ideas] Make Python code read-only
Chris Angelico
rosuav at gmail.com
Tue May 20 19:37:42 CEST 2014
On Wed, May 21, 2014 at 2:57 AM, Victor Stinner
<victor.stinner at gmail.com> wrote:
> * The sys module cannot be made read-only because modifying sys.stdout
> and sys.ps1 is a common use case.
I think this highlights the biggest concern with defaulting to
read-only. Currently, most Python code won't reach into another module
and change anything, but any program could monkey-patch any module at
any time. You've noted that modifying sys's attributes is common
enough to prevent its being made read-only; how do you know what else
will be broken if this change goes through?
For that reason, even though the read-only state would be the more
common one, I would strongly recommend flagging those modules which
_are_ read-only, rather than those which aren't. Then it becomes a
documentable part of the module's interface: "This module will be
frozen when Python is run in read-only mode". Setting that flag and
then modifying your own state would be a mistake on par with using
assert for crucial checks; monkey-patching someone else's read-only
module makes your app incompatible with read-only mode. Any problems
would come from use of *both* read-only mode *and* the __readonly__
flag, rather than unexpectedly cropping up when someone loads up a
module from PyPI and it turns out to depend on mutability.
Also, flagging the ones that have the changed behaviour means it's
quite easy to get partial benefit from this, with no risk. In fact,
you could probably turn this on for arbitrary Python programs, as long
as only the standard library uses __readonly__; going the other way,
having a single module that doesn't have the flag and requires
mutability would prevent the whole app from being run in read-only
mode.
With that (rather big, and yet quite trivial) caveat, though: Looks
interesting. Optimizing for the >99% of code that doesn't do weird
things makes very good sense, just as long as the <1% can be catered
for.
ChrisA
More information about the Python-ideas
mailing list