[Python-ideas] sys.py

Eric Snow ericsnowcurrently at gmail.com
Tue Sep 12 19:46:25 EDT 2017


The sys module is a rather special case as far as modules go.  It is
effectively a "console" into the interpreter's internal state and that
includes some mutable state.  Since it is a module, we don't have much
of an opportunity to:

* validate values assigned to its attributes [1]
* issue DeprecationWarning for deprecated attrs [2]
* alias attrs [2]
* replace get (and get/set) functions with properties
* re-organize sys [3]

One possible solution I've been toying with for quite a while [2] is
to rename the current sys module "_sys" and then add Lib/sys.py.  The
new module would proxy the old one (for backward-compatibility), but
also allow us to do all of the above (e.g. validate sys.modules).

I implemented this a few weeks ago:

  https://github.com/ericsnowcurrently/cpython/tree/sys-module
  (for the sake of comparison:
https://github.com/ericsnowcurrently/cpython/pull/2)

It uses the trick of replacing itself in sys.modules (though it could
just as well set __class__).  The only problem I've encountered is
code that uses "type(sys)" to get types.ModuleType.  Under my branch
"type(sys)" returns the ModuleType subclass.  Otherwise everything
looks fine.

Thoughts?

-eric


[1] I ran into this recently: https://bugs.python.org/issue31404
[2] I have plans for a low-level encapsulation of the import state and
a high-level API for the current import machinery as a whole.  As part
of that I'd like to be able to deprecate the current import state
attrs (e.g. sys.modules) and make them look up values from
sys.importstate.
[3] This has come up before, including
https://www.python.org/dev/peps/pep-3139/.  Also PEP 432 implies a
clearer structure for sys.


More information about the Python-ideas mailing list