importing os.path -- why does it work?

Steven D'Aprano steve at pearwood.info
Mon Jan 12 00:31:41 EST 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 
_find_and_load_unlocked
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/fnmatch.py'>



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

py> import collections.abc
py> collections.__package__
'collections'



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

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



By what wizardry does this work?


-- 
Steve



More information about the Python-list mailing list