jwelsh
jwelsh

Reputation: 308

Is the "os" module not subject to import shadowing?

In Python, one tries to avoid module name conflicts with the standard library, though Python 3 makes this better by getting rid of implicit relative imports in packages. So I was doing this intentionally, to test my understanding, and got a surprise.

test/
    __init__.py
    test.py:
        import os
        import string
    os.py:
        print("os")
    string.py:
        print("string")

Running from the parent directory:

$ python2 -m test.test
os
string

Implicit relative imports shadowing the system modules, as expected.

$ python3 -m test.test

Absolute imports in Python 3, as expected.

$ python test/test.py
string
$ python3 test/test.py
string

Huh? Why doesn't the "os" in the script directory shadow the system one?

(I figured this out upon typing the question, but I'll post anyway in case anyone else wonders.)

Upvotes: 1

Views: 91

Answers (1)

jwelsh
jwelsh

Reputation: 308

At startup, os is already loaded by the interpreter, just not available in the globals of the script/module. Much like when a module has already been imported somewhere in a package, but isn't available to a different submodule until you import it there.

In fact there are quite a few modules like this; try python -c "import sys; print('\n'.join(sorted(sys.modules)))".

Upvotes: 3

Related Questions