Python Libraries: What They Are and How to Use Them

Published on: July 10, 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

    Estatísticas e análise de dados com Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python Built-in Functions: Complete Guide

    Learn the most useful Python built-in functions for input, output, conversion, numbers, collections, iteration, sorting, validation, files, inspection, and objects.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Logo do Python com o texto 'requests' abaixo
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python Requests: Complete Beginner Guide

    Learn Python Requests from scratch: install the library, send GET and POST requests, work with parameters, headers, JSON, timeouts, sessions,

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Manipulação de datas e calendário em Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python datetime: Work with Dates and Times

    Learn Python datetime: create, parse, format, compare, and calculate dates and times, use timedelta, UTC, zoneinfo, and aware datetimes.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Barra de progresso com tqdm para scripts Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python tqdm: Add Progress Bars to Scripts

    Add progress bars to Python scripts with tqdm. Learn installation, loops, manual updates, files, pandas, nested bars, and practical options.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Uso do módulo random para gerar valores aleatórios em Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python random Module: Complete Beginner Guide

    Learn Python's random module: generate numbers, choose items, shuffle lists, sample data, use seeds, and know when to use secrets.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Manipulação moderna de arquivos usando pathlib em Python
    Libraries and Modules
    Foto de perfil de Leandro Hirt da Academify

    Python pathlib: Manage Files and Paths Easily

    Learn Python pathlib to create, inspect, read, write, rename, move, and delete files and folders with clean cross-platform code.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026