Home >Backend Development >Python Tutorial >What\'s the Key Difference Between Python Modules and Packages?
Understanding the Difference Between Modules and Packages in Python
Unlike many other programming languages, Python distinguishes between modules and packages. A clear understanding of their distinctions is crucial for effective Python coding.
Definition of a Module
A module in Python is nothing more than a single Python file. It is essentially a collection of code defined in that particular file. For instance, a file named "my_module.py" would define a module known as "my_module." Modules help organize code into logical units and enable importing and reusing them in other Python scripts.
Definition of a Package
A package, on the other hand, represents a collection of modules and sub-packages. It is represented by a directory containing multiple Python modules. Additionally, a file named "__init__.py" is required within the package directory to distinguish it from ordinary directories housing Python scripts. Packages may be nested at different levels, as long as each directory includes its own "__init__.py" file.
Distinctions Between Modules and Packages
While a module exists as a single Python file, a package constitutes a directory of Python modules. This distinction, however, only applies at the file system level. When importing either a module or a package, the generated Python object is always of type "module."
One notable difference is that importing a package only makes the variables, functions, and classes defined in its "__init__.py" file directly available. Sub-packages and modules within the package remain inaccessible through direct import.
Example
Consider the Python standard library's xml package as an illustration. Its xml directory holds an "__init__.py" file and four sub-directories. One of these sub-directories, etree, further contains an "__init__.py" file and a file called ElementTree.py.
Importing the various components would result in the following outcomes:
import xml type(xml) # <type 'module'> xml.etree.ElementTree # AttributeError: 'module' object has no attribute 'etree' import xml.etree type(xml.etree) # <type 'module'> xml.etree.ElementTree # AttributeError: 'module' object has no attribute 'ElementTree' import xml.etree.ElementTree type(xml.etree.ElementTree) # <type 'module'> xml.etree.ElementTree.parse # <function parse at 0x00B135B0>
From these examples, you can see that only after explicitly importing the sub-package or module (xml.etree.ElementTree) can you access its contents.
Note: Python also offers built-in modules that are implemented in C (e.g., sys). However, these fall outside the scope of your inquiry.
The above is the detailed content of What's the Key Difference Between Python Modules and Packages?. For more information, please follow other related articles on the PHP Chinese website!