Let's say I have a module foo
and a submodule foo.bar
. If I want to use a method in foo.bar
, do I need to import foo.bar
directly or is importing foo
sufficient?
For example, the following throws an error:
import foo
foo.bar.my_method()
and the following works:
import foo.bar
foo.bar.my_method()
But I'm not sure if this is generally what's needed, or if there's something wrong with my code itself. (I would think importing the submodule directly is generally needed... But I could have sworn I've seen code where it's not imported directly and still works fine.)
You'll need to import the submodule explicitly. Executing
import foo.bar
will automatically import the parent modulefoo
, and necessarily† bind the namefoo
, but the reverse is not true.Yes. Sometimes accessing a submodule works without the explicit import. This happens when a parent module itself imports the submodules. Never rely on that unless it's documented, because it may be an implementation detail and could change without warning after a library version upgrade.
As an example of a popular library which demonstrates both behaviors, look at
requests==2.18.4
. This package has submodules calledsessions
andhelp
(amongst others). Importingrequests
will makerequests.sessions
available implicitly, yetrequests.help
will not be available until explicitly imported. You'll find when the source code of the package init is executed that thesessions
submodule gets imported, but thehelp
submodule does not.† This makes sense, because subsequent use of
foo.bar
requires an attribute access on an existingfoo
object. Note thatfrom foo.bar import something
does not bind the namefoo
norfoo.bar
, though both modulesfoo
andfoo.bar
are imported and cached intosys.modules
.