GitHub

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 control
  • newsys.imports: related to imports and modules
  • newsys.io: the standard I/O streams
  • newsys.repl: REPL display control
  • newsys.interpreter: system information and installation details
  • newsys.memory: memory management tools
  • newsys.exceptions: exception handling
  • newsys.profile: profiling and introspection
  • newsys.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

Read the original on github.com ↗