I was trying out one of the Python standard library modules, let’s call it foo.bar.baz.
So I wrote a little script starting with
import foo.bar.baz
and saved it as foo.py.
When I executed the script I got an ImportError. It took me a while (I’m still learning Python), but I finally realized the problem was how I named the script. Once I renamed foo.py to something else, the problem went away.
So I understand that the import foo statement will look for the script foo.py before looking for the standard library foo, but it’s not clear to me what it was looking for when I said import foo.bar.baz. Is there some way that foo.py could have the content for that statement to make sense? And if not, why didn’t the Python interpreter move on to look for a directory hierarchy like foo/bar with the appropriate __init__.py‘s?.
An import statement like
import foo.bar.bazfirst importsfoo, then asks it forbar, and then asksfoo.barforbaz. Whetherfoowill, once imported, be able to satisfy the request forbarorbar.bazis unimportant to the import offoo. It’s just a module. There is only onefoomodule. Bothimport fooandimport foo.bar.bazwill find the same module — just like any other way of importing thefoomodule.There is actually a way for
footo be a single module, rather than a package, and still be able to satisfy a statement likeimport foo.bar.baz: it can add"foo.bar"and"foo.bar.baz"to thesys.modulesdict. This is exactly what theosmodule does withos.path: it imports the right “path” module for the platform (posixpath,ntpath,os2path, etc), and assigns it to thepathattribute. Then it doessys.modules["os.path"] = pathto make that module importable asos.path, so a statement likeimport os.pathworks. There isn’t really a reason to do this —os.pathis available without importing it as well — but it’s possible.