What is the difference between package and module in Python?

Asked

Viewed 3,178 times

7

Is there a difference between a package and a module in Python? If there is a difference, it is possible to give examples of packages and modules?

1 answer

13


Module

In the documentation says:

A module is a file containing Python Definitions and statements. The file name is the module name with the suffix . py appended.

I mean, a file foo.py is considered a Python module if it has language definitions and instructions. That is, any Python file can be considered a module. For this case, the module name would be foo, defined by the file name, without the extension.

For example:

# foo.py

def foonction ():
    print("Função no módulo foo")

In any other Python file, you can import the module and use its settings:

# main.py

import foo

if __name__ == "__main__":
    foo.foonction() # Função no módulo foo

In the glossary there is:

An Object that serves as an organizational Unit of Python code. Modules have a namespace containing arbitrary Python Objects. Modules are Loaded into Python by the process of importing.

That is, module is an object (in Python everything is object) that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects (instances, classes, functions, etc.).

Bundle

In the documentation says:

Packages are a way of structuring Python’s module namespace by using "dotted module Names".

That is, the package is the way to define namespaces for modules, allowing numerous modules of the same name to coexist without interference. Basically, a Python package is a directory that contains modules:

sopt/
  __init__.py
  foo.py

To use a package module, simply import it using the dotted names:

# main.py

import sopt.foo

if __name__ == "__main__":
    sopt.foo.foonction() # Função no módulo foo

The difference between a common directory for a Python package is precisely the presence of the file __init__.py. Without it, the directory will not be considered a package and the modules will be inaccessible.

In the glossary there is:

A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an __path__ attribute.

That is, the package is a module that contains submodules or, recursively, subpackages. Technically, a package is a Python module that has the attribute __path__.

That is why even if the documentation mentions some functionality for modules, it is allowed to use it over packages as well, because the package is a module. For example, using the parameter -m mod in charge python:

python -m django --version

as discussed in this another question.

  • In the most recent versions, the file __init__.py is optional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.