Summary
In this chapter, we looked at a number of the more advanced aspects of working with modules and packages in Python. We saw how a try..except
statement can be used to implement optional imports, and how an import
statement can be placed inside a function so that the module only gets imported when that function is executed. We then learned about the module search path and how you can modify sys.path
to change the way the Python interpreter looks for modules and packages.
We then looked at some of the gotchas related to the use of modules and packages. We learned about name masking, where you define a module or package with the same name as a module or package in the Python Standard Library, which can lead to unexpected failures. We looked at how giving a Python script the same name as a Standard Library module can also cause name masking problems, and how adding a package directory or sub-directory to sys.path
can cause a module to be loaded twice, leading to subtle problems with global...