Modules and packages
By now, you should be fairly comfortable with organizing your Python code into modules and then importing and using these modules in other modules and programs. This is only a taste of what can be done, however. Let's briefly review what Python modules and packages are before looking closer at how they work.
As we have seen, a module is simply a Python source file. You can import the module using the import
statement:
import my_module
Once this is done, you can refer to any functions, classes, variables, and other definitions within the module by prepending the module name to the item, for example:
my_module.do_something() print(my_module.variable)
In Chapter 1, Introducing Modular Programming, we learned that a Python package is a directory containing a special file named __init__.py
. This is called the
package initialization file and identifies the directory as a Python package. The package also typically contains one or more Python modules, for example:
To import the modules...