A proof of concept for a thought experiment:
what if Python's sys module were a package with submodules?
What it does
newsys splits everything in sys into 9 themed submodules:
newsys.cli: command-line argument handling and program controlnewsys.imports: related to imports and modulesnewsys.io: the standard I/O streamsnewsys.repl: REPL display controlnewsys.interpreter: system information and installation detailsnewsys.memory: memory management toolsnewsys.exceptions: exception handlingnewsys.profile: profiling and introspectionnewsys.runtime: interpreter runtime behavior
Nothing is copied out of sys.
The flat name, the submodule name, and the real sys attribute are always the same object, and a write to any one of them updates all three:
>>> import sys, newsys >>> newsys.stdout is newsys.io.stdout is sys.stdout True >>> newsys.cli.argv = ["demo"] >>> sys.argv ['demo'] >>> newsys.argv ['demo'] >>> sys.argv = [''] >>> newsys.cli.argv ['']
So code that monkey patches sys.stdout (the way contextlib.redirect_stdout does) would keep working after a reorganization like this one.
How it works
Each submodule in newsys gets a ProxyModule subclass (see newsys/_proxy.py) that reads and writes its own names straight through to sys, and newsys itself gets a subclass that forwards each flat name to whichever submodule owns it.
Running the tests
$ python3 test_newsys.py