[Python-ideas] Make Python code read-only

Chris Angelico rosuav at gmail.com
Wed May 21 04:20:14 CEST 2014


On Wed, May 21, 2014 at 11:42 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Wed, May 21, 2014 at 03:37:42AM +1000, Chris Angelico wrote:
>
>> 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.
>
> "99% of Python code doesn't do weird things..."
>
> It seems to me that this is a myth, or at least unjustifiable by the
> facts as we have seen it. Victor's experiment shows 25 modules from the
> standard library are modifiable, with 139 read-only. That's more like
> 15% than 1% "weird".
>
> I don't consider setting sys.ps1 and sys.stdout to be "weird", which is
> why Victor has to leave sys unlocked.

Allow me to clarify. A module mutating its own globals is not at all
weird; the only thing I'm calling weird is reaching into another
module's globals and changing things. In a few rare cases (like
sys.ps1 and sys.stdout), this is part of the documented interface of
the module; but if (in a parallel universe) Python were designed such
that this sort of thing is impossible, it wouldn't be illogical to
have a "sys.set_ps1()" function, because the author(s) of the sys
module *expect* ps1 to be changed. In contrast, the random module
makes use of a bunch of stuff from math (importing them all with
underscores, presumably to keep them out of "from random import *",
although __all__ is also set), and it is NOT normal to reach in and
change them. And before you say "Well, that has an underscore, of
course you don't fiddle with it", other modules like imaplib will
happily import without underscores - is it expected that you should be
able to change imaplib.random to have it use a different random number
generator? Or, for that matter, to replace some of its helper
functions like imaplib.Int2AP? That, I think, would be considered
weird.

So there are 15% that change their own globals, which is fine. In this
particular instance, we can't optimize for the whole of the 99%, but I
maintain that the 15% is not all "weird" just because it's not
optimizable. How many modules actually expect that their globals will
be externally changed?

ChrisA


More information about the Python-ideas mailing list