In Python, the difference between a module and a package is significant. We will divide this Answer into two sections:
Explaining modules
Explaining packages
A module is a single Python file containing code. It typically consists of functions, classes, and variables related to a specific task, and it can be imported into other Python scripts or modules that can reuse its functionality. Modules can be imported directly into other Python scripts or modules using the import
statement.
An example of a module is given below:
def myModule(name): print("The module imported is called "+ name)
The code above is explained as follows:
Line 1: Import the examplemodule
module contained in examplemodule.py
.
Line 3: The myModule
function of examplemodule
is being called with the value "Tech
".
In contrast, a package is a collection of related modules organized in a directory hierarchy. Along with modules, its directory contains a special file called __init__.py
that is executed when the package is imported. The __init__.py
file can contain initialization code, package-level variables, and module imports.
Unlike regular modules, packages can be imported as from package import module
. And we can auto-import the modules with the package if imports are added in __init__.py
. We can import them with .
notation as shown in the example below:
import pkg pkg.firstmodule.invoke() pkg.secondmodule.invoke()
Free Resources