What is the difference between a package and a module in Python?

4

Is there a difference between a package and a module in Python? If there is a difference, can you give examples of packages and modules?

    
asked by anonymous 25.05.2017 / 02:00

1 answer

9

Module

At documentation says:

  

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

That is, a foo.py file 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 filename, 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.).

Package

At documentation says:

  

Packages are a way of structuring Python's module namespace by using "dotted module names".

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

sopt/
  __init__.py
  foo.py

To use a module in a package, 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 __init__.py file. Without it, the directory will not be considered a package and the modules will be inaccessible.

In the glossary there are:

  

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 sub-modules or, recursively, sub-packages. Technically, a package is a Python module that has the __path__ attribute.

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

python -m django --version

As discussed this another question.

    
25.05.2017 / 02:17