importing os.path -- why does it work?

Steven D'Aprano steve at
Mon Jan 12 06:31:41 CET 2015

Using the `spam.eggs` syntax for modules only works if spam is a package 
and eggs is a sub-package or module. For example, this fails:

py> import glob.fnmatch
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1516, in 
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'glob.fnmatch'; glob is not a package

even though fnmatch is a module in glob's namespace:

py> import glob
py> glob.fnmatch
<module 'fnmatch' from '/usr/local/lib/python3.3/'>

On the other hand, if you have a proper package, it works:

py> import
py> collections.__package__

But bizarrely, you can import os.path this way!

py> import os.path
py> os.path
<module 'posixpath' from '/usr/local/lib/python3.3/'>
py> os.__package__

By what wizardry does this work?


More information about the Python-list mailing list