I\'m having difficulty understanding the import statement and its variations.
Suppose I\'m using the lxml
module for scraping websites.
The followin
When you import
a package, the interpreter looks up the package on the pythonpath, then if found, parses and runs the package's __init__.py
, building a package object from it, and inserts that object in to sys.modules
. When importing
a module, it does the same thing, except it creates and adds a module object. When you subsequently attempt to access an attribute (aka a member method, class, submodule, or subpackage), it retrieves the corresponding object from sys.modules
and attempts a getattr
on the module or package object for the child you want. However, if the child is a submodule or subpackage that has not yet been imported
, it has not been added to sys.modules
or the module or package's attribute list, so you get an AttributeError
. Thus, you have to explicitly import a module or package, either in your code, or delegated in a package's __init__.py
for it to be available at runtime on its parent.