Last Updated on 2021-10-11 by Clay
When we are chatting with friends with CS backgrounds, we may hear them said: “This time we should use the A package!“, “Maybe we should consider importing B module…” So, what exactly is it? what is package? what is module? and what is the difference between them?
This problem has been troubled for a long time when I first started to learn. As I wrote more and more codes, although I didn’t specifically search their definition, I understood the difference between package and the module.
This article was written just for the former self. I also hope can help some people who are as troubled as me.
Package and Module
Any python files (used .py extensions) can be seen as a module, the module name is the file name.
A package usually contains an additional python module directory file __init__.py
.
Therefore, the difference between package and module only exists at the system level, or the architecture scale.
But no matter you import a package or a module in the program, the result of using the type()
function is always module.
The following is an example, my_module.py
is a module.
import csv
import my_module
# Type
print(type(csv))
print(type(my_module))
Output:
<class 'module'>
<class 'module'>
This is why some program developers claim that a package is also a type of module, and think this is an important concept.
According to python official document (https://docs.python.org/3/glossary.html#term-package), the definition of package is::
A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an
__path__
attribute.
This is a very clear definition, and we can also think that a package has more complex functions than a module, and often contains a large number of modules.
References
- https://docs.python.org/3/glossary.html#term-package
- https://stackoverflow.com/questions/7948494/whats-the-difference-between-a-python-module-and-a-python-package