Faking stdlib

Chris Angelico rosuav at gmail.com
Thu Oct 1 03:17:07 EDT 2020


On Thu, Oct 1, 2020 at 5:02 PM Antoon Pardon <antoon.pardon at vub.be> wrote:
>
> I'm playing with the following idea.
>
> Have the main program do some kind of preparations so that all further
> modules can import the standard modules via stdlib. So instead of
>
>      import sys
>      from itertools import chain
>
> I could do
>
>      import stdlib.sys
>      from stdlib.itertools import chain
>

My first thought was __getattr__ on a package, but that doesn't seem to work:

# stdlib/__init__.py
def __getattr__(name):
    return __import__(name)

>>> import stdlib.math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'stdlib.math'
>>> from stdlib import math
>>> math
<module 'math' from
'/usr/local/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so'>

It may be necessary to use an import hook.

ChrisA


More information about the Python-list mailing list