Python imports are confusing, but I thought I finally understood them until I stumbled upon this behaviour (in 3.9.1). What is happening here?
Take this package structure:
countries/
├── __init__.py # from . import greece
├── greece.py
└── spain.py
If I do import countries
, the namespace dir(countries)
only contains greece
, as expected.
But if instead I start my session with:
from countries import spain
import countries
The namespace dir(countries)
contains both greece
and spain
!
I know that __init__.py
is run under the hood when I do the first import. What I don't understand is how python remembers to include both greece
and spain
in the countries
namespace. Is it keeping the countries
namespace saved somewhere under the hood after running from countries import spain
, and then running import countries
just adds it to the local namespace?