What is the difference between a python module and a python package?

PythonServer Side ProgrammingProgramming

Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules.

For example, in the datetime module, there is a submodule called date. When you import datetime, it won't be imported. You'll need to import it separately.

>>> import datetime
>>> date.today()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'date' is not defined
>>> from datetime import date
>>> date.today()
datetime.date(2017, 9, 1)
Published on 19-Dec-2017 11:16:24