Junior
What is the difference between a module and a package in Python?
sobes.tech AI
Answer from AI
In Python:
-
Module — is a separate file with a
.pyextension that contains code (functions, classes, variables). For example,math.pyis a module. -
Package — is a directory that contains an
__init__.pyfile and can contain multiple modules and subdirectories (subpackages). Packages are used to organize modules into a hierarchical structure and manage namespaces.
Example:
my_package/ # package
__init__.py # package initialization file
module1.py # module
sub_package/ # subpackage
__init__.py
module2.py
Import:
from my_package import module1
from my_package.sub_package import module2
Thus, a module is a unit of code, and a package is a way to group modules into a structure with a namespace.