Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does importing a python module not import nested modules?

If I do this:

import lxml 

in python, lxml.html is not imported. For instance, I cannot call the lxml.html.parse() function. Why is this so?

like image 826
dangerChihuahua007 Avatar asked Feb 15 '12 23:02

dangerChihuahua007


1 Answers

Importing a module or package in Python is a conceptually simple operation:

  1. Find the .py file corresponding to the import. This involves the Python path and some other machinery, but will result in a specific .py file being found.

  2. For every directory level in the import (import foo.bar.baz has two levels), find the corresponding __init__.py file, and execute it. Executing it simply means running all the top-level statements in the file.

  3. Finally, the .py file itself (foo/bar/baz.py in this case) is executed, meaning all the top-level statements are executed. All the globals created as a result of that execution are bundled into a module object, and that module object is the result of the import.

If none of those steps imported sub-packages, then those sub-packages aren't available. If they did import sub-packages, then they are available. Package authors can do as they wish.

like image 55
Ned Batchelder Avatar answered Oct 18 '22 09:10

Ned Batchelder