Back to Learning Area

External Code Libraries (Packages)

Including external libraries without triggering the next security nightmare.

  • Fundamentals
  • 13 min
  • Beginner

Plain Language

This preview is in Plain Language. The whole portal is also available in Plain Language. You can change the language at the top. Or use the button below. Our Plain Language texts are AI-assisted and editorially reviewed. They follow the core principles of easy-to-read language, but they are not certified Easy Read: a review panel of people with learning difficulties does not test them.

Preview: Packages and libraries in Python

What are packages?

Python has a library with finished programs. Library means: a collection of code. Other programmers write this code. You can use it for free. This saves you a lot of work.

How you get packages

You get packages with the command pip install. Pip is a tool for Python. PyPI is the address for packages. PyPI means: a large collection of Python packages. More than 900,000 packages are ready there.

Why Python for AI?

Python is the most important language for AI. It has many packages from experts. NumPy calculates with large number tables. Pandas sorts and analyzes data. PyTorch trains AI models.

You have learned variables, loops, functions — you can write Python. But here is the secret of professional development: most real-world projects are around 30% your code and 70% libraries others already built.

This article shows you the three layers of Python's code universe: what is already included, how to add what is missing, and why this ecosystem made Python the world's dominant AI language.

Standard Library & Imports

Definition

Module and Package

Analogy

When you move into a new apartment, a basic toolbox is already in the closet — hammer, screwdrivers, tape measure. You can hang pictures and assemble furniture immediately without visiting a hardware store. Python's standard library is that toolbox: math is the tape measure, json the screwdriver set, os the flashlight for exploring the building.

A real toolbox has physical space limits. Python's standard library has grown over the years and contains specialised modules (sqlite3, email, tkinter) that go far beyond basics. Also, a physical toolbox never requires choosing how you pull out a tool — Python's three import forms affect namespace behaviour.

import math

Full module loaded. Access via math.sqrt(144). The name math serves as a namespace — no name conflicts with your own variables.

from random import randint

Only randint loaded. Direct call: randint(1, 6). Shorter, but with many imports you can lose track of origins.

Note

Three Import Styles

import math
print(math.sqrt(144))           # 12.0

from random import randint
print(randint(1, 6))             # e.g. 4

import json as j
print(j.dumps({"name": "Ada"}))  # {"name": "Ada"}

All three modules are available without any installation — they are part of the standard library. You only need the right import line.

Caution

Misconception: import Downloads Code from the Internet

import only loads modules that are already present on your computer — either from the standard library or from packages previously installed via pip. import never contacts the internet. Downloading is a separate step using pip.

When Python executes import math, it searches a list of directories in sys.path. This list includes: the directory of your script, standard library paths, and the site-packages directory (where pip installs).

import sys
print(sys.path)
# ['/home/ada/project', '/usr/local/lib/python3.12', '/usr/local/lib/python3.12/lib-dynload',
#  '/usr/local/lib/python3.12/site-packages']

On first import, Python compiles the module into bytecode and stores it in the __pycache__ folder. On subsequent imports, the cache is used — this speeds up startup.

pip & PyPI — The App Store for Python

Definition

pip and PyPI

Analogy

PyPI is like an app store: you search for functionality, type one install command, and it is ready to use. But unlike phone apps that run in isolated sandboxes, Python packages share the same installation directory. If Project A needs LibX version 2 and Project B needs LibX version 3, they clash — like two apps fighting over the same file.

An app store is curated and reviewed by a company. PyPI is open — anyone can upload. There is no mandatory quality gate, so you must learn to evaluate packages yourself (download counts, maintenance activity, documentation).

Note

The pip Workflow: Install → Import → Use

  1. 1. pip install requests — Download and install the package from PyPI
  2. 2. import requests — Make the installed package available in your code
  3. 3. requests.get(url).status_code — Use the packagehere: send an HTTP request

Note

requirements.txt — Making Dependencies Reproducible

Professional projects list all required packages in a requirements.txt file:

requests==2.34.2
pandas>=2.0.0
numpy>=1.24.0

One single command — pip install -r requirements.txt — installs all dependencies. And dependencies are transitive: when you install pandas, numpy comes along automatically because pandas needs it internally. Watch out: == fixes exactly one version, >= only sets a lower bound. pandas>=2.0.0 already installs pandas 3 today. The file only becomes truly reproducible once every package is pinned with ==, for example via pip freeze > requirements.txt.

Caution

Misconception: import Automatically Installs Missing Packages

import and pip install are strictly separate operations. The import mechanism only searches local directories (standard library + site-packages) — it never contacts PyPI. Without prior installation via pip, you get a ModuleNotFoundError.

Anyone can upload packages to PyPI. Before installing an unknown package, check these signals:

Download counts (popular packages are better tested), last update (abandoned projects are risky), documentation quality (good docs = active maintenance), GitHub stars and issues (community engagement), and security audits (for sensitive applications). The rule: the more people use a package, the more likely bugs are found and fixed quickly. Popularity is no protection against attacks, though: in March 2026, two tampered versions of the widely used AI library litellm appeared on PyPI and stole credentials. So pin exact versions, so that the newest release does not slip in unchecked. And check every package name on pypi.org before you install it: attackers deliberately register typo names like “reqeusts” and names that AI assistants sometimes simply make up.

The Ecosystem — Why Python Became the AI Language

Python's Three-Layer Model

External Packages (PyPI) 900,000+ packages from the community
Standard Library 200+ modules that ship with Python
Your Code The logic you write yourself

Each package is like a specialised LEGO brick manufactured by experts. You assemble them into custom creations without needing to know how plastic is moulded — just as you build an ML pipeline without writing C matrix multiplication code.

But LEGO bricks always fit together (standard stud size). Python packages can have version conflicts and incompatible dependencies. And LEGO is curated by one company, while PyPI is an open bazaar — ranging from industry-grade libraries to abandoned hobby projects.

NumPy Arrays and linear algebra in C/Fortran
pandas DataFrames for data analysis
scikit-learn Classical machine learning
PyTorch Deep learning with GPU acceleration
Django Web framework for complex applications
requests HTTP requests made simple

Note

Python as a Glue Language

Python as an interpreter is relatively slow. But its strength lies not in speed but in its role as a "glue language": Python provides the user-friendly interface while the heavy computation runs in compiled C/C++ or CUDA underneath.

import pandas as pd
df = pd.read_csv("data.csv")
print(df.describe())   # Statistical summary

from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X, y)        # ML model in one line

Behind these few Python lines are thousands of lines of optimised C/Fortran code. Python gives the commands — the actual computation happens in compiled code.

Caution

Misconception: Python Is Too Slow for AI

Python itself is slow for raw loops. But AI workloads run in C/C++/CUDA behind library calls. Python is the steering wheel, not the engine. The actual matrix multiplications, gradient computations, and data transformations happen in compiled code — Python just orchestrates them.

Interactive: Package Manager Checklist

Answer the following questions about your Python project. At the end, you will receive a recommendation for which dependency management tool best fits your situation.

Package Manager Checklist

Find out which package management tool best fits your Python project.

1.Do you work on multiple Python projects simultaneously?
Different projects often need different package versions — isolation prevents conflicts.
2.Do your projects require different Python versions?
e.g. Project A needs Python 3.12, Project B needs Python 3.14.
3.Must other developers be able to set up your project reproducibly?
Teamwork, CI/CD and deployment require pinned dependencies.
4.Do you install packages from sources other than PyPI (e.g. conda-forge)?
Some scientific packages (e.g. CUDA toolkit, MKL) are easier to install via Conda.
5.Are you developing a library that others will install via pip?
Library development requires build tools and metadata (pyproject.toml).
6.Do you need automatic dependency locking (exact versions of all transitive dependencies)?
Lock files guarantee that exactly the same versions are installed on every machine.
0 / 6 answered

Note

Key Takeaways

  1. Python's standard library covers everyday tasks (math, JSON, files, dates) — always check the "batteries included" before installing externally.
  2. pip install downloads from PyPI; import loads what is already installed locally — these are strictly separate steps.
  3. Python dominates AI not because of raw speed but because its ecosystem wraps high-performance C/C++ code behind a clean, beginner-friendly API.

Check

Quiz: Packages and Imports

Not completed

What is the difference between import and pip install?

Select one answer

Answer Key: 1) C · 2) B · 3) C · 4) C

Check

Checkpoint

Can you explain this in your own words? Tick what you've got.

0 of 3 done