Python Libraries: Modules, Packages, and pip

Updated on: August 21, 2026
Reading time: 6 minutes
Logo do Python com expressão pensativa sobreposto a uma biblioteca com estantes cheias de livros, representando o conceito de bibliotecas em Python

Python libraries are reusable collections of code that solve common problems. Instead of implementing every feature from the beginning, a developer can import a tested module for dates, files, web requests, data analysis, charts, automation, or thousands of other tasks.

This guide explains the terms library, module, package, and framework; shows how to use the standard library; demonstrates safe installation with pip and virtual environments; and provides practical criteria for choosing external dependencies.

Why libraries matter

Imagine writing a program that must parse JSON, calculate statistics, read CSV files, connect to a website, and create a chart. Building every component yourself would take a long time and introduce avoidable errors. Libraries provide reusable building blocks so you can focus on the specific problem your application solves.

Libraries also create a shared vocabulary. A team familiar with Pandas, Requests, or Pytest can understand a project more quickly because those tools follow documented interfaces and established patterns.

Module, package, library, and framework

These terms are related but not identical:

  • Module: usually one Python file containing variables, functions, or classes.
  • Package: a directory structure that groups importable modules and subpackages.
  • Library: a general term for reusable code, often distributed as one or more packages.
  • Framework: a larger structure that controls part of the application’s flow and expects your code to fit its conventions.

The official Python modules tutorial explains import behavior, packages, search paths, and module execution.

The Python standard library

Python ships with a large standard library. These modules are available after Python is installed and normally require no pip command. Examples include:

  • pathlib for filesystem paths;
  • json for JSON encoding and decoding;
  • csv for CSV files;
  • datetime for dates and times;
  • statistics for common statistical calculations;
  • sqlite3 for SQLite databases;
  • logging for application logs;
  • unittest for automated tests.

The complete Python standard library reference documents every included module.

Import a standard-library module

import statistics

scores = [72, 85, 91, 68, 84]
print(statistics.mean(scores))
print(statistics.median(scores))

The module name becomes available in the current file, and its functions are accessed with dot notation. This makes the source of each function clear.

Import a specific name

from pathlib import Path

report = Path("reports") / "sales.csv"
print(report)

Importing a specific name can make code concise when that name is used often. Our Python pathlib guide covers files, directories, reading, writing, and cross-platform paths.

Use an import alias

Some libraries have conventional aliases:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Aliases reduce repetition without hiding the library. Follow well-known conventions so other developers recognize the code immediately.

Avoid wildcard imports

from math import *  # Avoid in ordinary application code.

A wildcard import adds many unknown names to the current namespace. It can overwrite an existing name and makes it difficult to see where a function came from. Prefer import math or import the exact names required.

External libraries and PyPI

Third-party libraries are developed outside the Python standard library. Many are published on the Python Package Index (PyPI). Examples used throughout Academify include:

Create a virtual environment first

Installing every package into one global Python environment leads to version conflicts. Isolate each project:

python -m venv .venv

After activation, packages installed with pip belong to that environment. The complete process is explained in our Python virtual environments guide.

Install a package with pip

python -m pip install requests

Using python -m pip explicitly connects pip to a Python interpreter. This helps avoid the common situation where pip installs into one environment while the editor runs another.

Our pip installation guide covers upgrades, uninstalling, version selection, and common errors.

Verify the installation

import requests
print(requests.__version__)

If the import fails, inspect the interpreter path:

import sys
print(sys.executable)

Then compare it with the environment where pip installed the package.

Read package documentation

Do not guess function arguments from unrelated examples. Good packages provide:

  • installation instructions;
  • a quick-start tutorial;
  • API reference pages;
  • supported Python versions;
  • release notes and migration guides;
  • security reporting instructions.

Prefer the project’s official documentation over copied code with no version context.

Save project dependencies

A simple project can record installed versions:

python -m pip freeze > requirements.txt

Another person can install them with:

python -m pip install -r requirements.txt

pip freeze records every installed distribution, including indirect dependencies. For a long-lived application, consider a dependency management workflow that distinguishes direct requirements from locked transitive versions.

Choose a trustworthy library

Before adding a dependency, evaluate:

  • Purpose: does it solve a real project need?
  • Documentation: are the examples and API reference clear?
  • Maintenance: are releases, issues, and security updates active?
  • Compatibility: does it support your Python and operating-system versions?
  • License: is it compatible with your intended use?
  • Dependencies: does it add a large or risky dependency tree?
  • Community and governance: is there an identifiable project with transparent source code?

Download statistics alone do not guarantee security or quality.

Protect against package-name mistakes

Typosquatting packages use names similar to popular libraries. Copy the exact installation name from official documentation, inspect the PyPI project page, and avoid commands from unknown comments or videos.

A package’s import name can differ from its distribution name. For example, the name used with pip is not always identical to the name in the import statement.

Pin versions thoughtfully

You can request a specific version:

python -m pip install requests==2.32.3

Exact pins improve repeatability, but permanent old pins can miss security fixes. Applications should test upgrades regularly. Libraries intended for other developers often specify compatible version ranges rather than one exact environment.

Upgrade and uninstall packages

python -m pip install --upgrade requests
python -m pip uninstall requests

Review release notes before major upgrades. A new major version can remove or change previously supported interfaces.

Inspect installed packages

python -m pip list
python -m pip show requests
python -m pip check

pip check reports incompatible installed requirements. It is a useful diagnostic after changing several versions.

Create your own module

A library begins with reusable code. Create calculations.py:

def calculate_discount(price: float, percentage: float) -> float:
    if price < 0:
        raise ValueError("price cannot be negative")
    if not 0 <= percentage <= 100:
        raise ValueError("percentage must be between 0 and 100")
    return price * (1 - percentage / 100)

Import it from another file in the same project:

from calculations import calculate_discount

final_price = calculate_discount(200, 15)
print(final_price)

Adding type hints, a docstring, and tests makes the module easier to reuse. See the docstrings guide and the Pytest material linked earlier.

The if __name__ pattern

A module can provide reusable functions and also include a demonstration that runs only when executed directly:

def greet(name: str) -> str:
    return f"Hello, {name}!"


if __name__ == "__main__":
    print(greet("Alex"))

Importing this module makes greet() available without running the demonstration.

Common beginner mistakes

  • Naming a file after a library: files such as requests.py or json.py can shadow the real package.
  • Installing into the wrong interpreter: compare sys.executable with the selected environment.
  • Copying outdated syntax: check the documentation for the installed version.
  • Committing a virtual environment: add .venv/ to .gitignore and commit dependency files instead.
  • Ignoring import errors: read the traceback and confirm spelling, installation, environment, and local file names.
  • Adding a dependency for a tiny task: the standard library or a small local function may be enough.

When not to use a library

A dependency has a maintenance cost. Avoid adding one when a clear ten-line function solves the problem safely, when the package is abandoned, when its license is unsuitable, or when the project cannot accept its security and deployment implications.

On the other hand, do not reimplement complex cryptography, parsers, network protocols, or database drivers casually. Established, reviewed libraries are usually safer than homegrown versions of specialized infrastructure.

Conclusion

Python libraries turn reusable code into practical building blocks. Begin with the standard library, isolate third-party dependencies in a virtual environment, install exact package names from trusted sources, and read official documentation. Evaluate maintenance, compatibility, license, and security before adding a dependency, then record the environment so the project can be reproduced later.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Document and inbox representing local email stores with Python mailbox
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python mailbox: Local Email Stores

    Learn Python mailbox to read, create, and migrate Maildir, mbox, and MH stores with locking, flags, message parsing, and safe

    Ler mais

    Tempo de leitura: 5 minutos
    12/08/2026
    Text editor representing formatting with Python textwrap
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python textwrap: Format Text

    Learn Python textwrap to wrap, fill, shorten, indent, and dedent text with controlled width, whitespace, long words, and reusable settings.

    Ler mais

    Tempo de leitura: 4 minutos
    10/08/2026
    Folder and magnifying glass representing file-name filters with Python fnmatch
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python fnmatch: Filter File Names

    Learn Python fnmatch to filter file names with shell wildcards, control case sensitivity, exclude patterns, and distinguish glob from regex.

    Ler mais

    Tempo de leitura: 5 minutos
    10/08/2026
    Monitor with binary data representing compact numeric arrays in Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python array: Compact Numeric Data

    Learn Python array for compact numeric storage, binary files, byte order, memory views, and safe buffer interoperability.

    Ler mais

    Tempo de leitura: 6 minutos
    10/08/2026
    Color wheel representing RGB, HSV, and HLS conversions with Python colorsys
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python colorsys: RGB, HSV, and HLS

    Learn Python colorsys to convert colors between RGB, HSV, HLS, and YIQ, generate palettes, and avoid scale and precision mistakes.

    Ler mais

    Tempo de leitura: 5 minutos
    09/08/2026
    Configuration icon representing plist files with Python plistlib
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    plistlib: Read and Write Apple Plist Files

    Learn Python plistlib to read and write XML and binary plist files, validate data, handle dates, bytes, and UIDs safely.

    Ler mais

    Tempo de leitura: 6 minutos
    08/08/2026