After import, some submodules are accessible and some aren't

Steve D'Aprano steve+python at pearwood.info
Fri Oct 28 20:24:24 EDT 2016


On Sat, 29 Oct 2016 08:24 am, John Gordon wrote:

> After importing a module, I can access some of its submodules directly
> but others require an explicit import of the submodule.
[...]
> Why the difference?

Ask the author of the package.


Try this experiment: create a package called "imptest" with this directory
structure:


imptest/
+--  __init__.py
+--  spam.py
+--  eggs.py


That is, a single directory called "imptest", containing three
files "__init__.py" (that's TWO leading and trailing
underscores), "spam.py" and "eggs.py".

spam and eggs can remain blank. Inside __init__.py put:

import imptest.spam
print(spam)


Save and close the file, and then launch Python. Try:


import imptest
imptest.spam  # this should work
imptest.eggs  # this should fail

import imptest.eggs
imptest.eggs  # this should now work




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list