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:
pathlibfor filesystem paths;jsonfor JSON encoding and decoding;csvfor CSV files;datetimefor dates and times;statisticsfor common statistical calculations;sqlite3for SQLite databases;loggingfor application logs;unittestfor 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 pltAliases 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:
- Requests for HTTP communication;
- Pandas for tabular data;
- NumPy for numerical arrays;
- Matplotlib for static charts;
- Plotly for interactive charts;
- Pytest for testing.
Create a virtual environment first
Installing every package into one global Python environment leads to version conflicts. Isolate each project:
python -m venv .venvAfter 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 requestsUsing 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.txtAnother person can install them with:
python -m pip install -r requirements.txtpip 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.3Exact 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 requestsReview 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 checkpip 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.pyorjson.pycan shadow the real package. - Installing into the wrong interpreter: compare
sys.executablewith the selected environment. - Copying outdated syntax: check the documentation for the installed version.
- Committing a virtual environment: add
.venv/to.gitignoreand 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.






