Search code examples
pythonpython-internals

Why can Python not see previously imported modules?


Suppose there are two files a.py and b.py. Inside them are the following:

# a.py
from b import foo

foo()

# b.py
import os

def foo():
    print(os.cwd())

This works just fine, but why is a.py unable to see the imports of b.py implicitly for its own use:

# a.py
import b

def bar():
    print(os.cpu_count())  # fails

b.foo()
bar()

# b.py
import os

def foo():
    print(os.cwd())

I am reading the import system docs but haven't been able to figure this out. The os import exists in the namespace of b.py but it's not available to a.py and I am unsure why. The globals() method is at the module level, so given the rules, is there no sharing of imports between modules (without using __all__ and * imports)? Does each module get its own import namespace?


Solution

  • Each module has its namespace. The import statement does two things: if a module is not yet imported in the current process, it is loaded and executed. After that its name is bound to the local namespace where the import statement is.

    If a module already had been imported in the same process, it is not reloaded, but the names in the import statement are correctly bound by the import statement.

    The correct thing to do is to add another import os on your a module - but if you do import b you can use b.os.cwd() (as "os" is a bound name in the module b after it is executed)