External Code Libraries (Packages)

Including external libraries without triggering the next security nightmare.

Fundamentals 13 min Beginner April 26, 2026

You have learned variables, loops, functions — you can write Python. But here is the secret of professional development: most real-world projects are 10% your code and 90% 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

Module and Package

AnalogyDefinition
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 keeps growing with each version 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.

Three Import Styles

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

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

import json
print(json.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.

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 current directory, standard library paths, and the site-packages directory (where pip installs).

import sys
print(sys.path)
# ['.', '/usr/lib/python3.12', '/usr/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

pip and PyPI

AnalogyDefinition
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).

The pip Workflow: Install → Import → Use

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

requirements.txt — Making Dependencies Reproducible

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

requests==2.31.0
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.

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.

The Ecosystem — Why Python Became the AI Language

Python's Three-Layer Model

External Packages (PyPI) 750,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

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.

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.10, Project B needs Python 3.12.
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

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.

Quiz: Packages and Imports

Question 1 / 4
Not completed

What is the difference between import and pip install?

Select one answer
Answer Key: 1) C · 2) B · 3) C · 4) C

Checkpoint

  • You run import requests in a fresh Python installation and get a ModuleNotFoundError. Why? What must you do first?
  • A colleague sends you a project with a requirements.txt. You clone it and run the script — it crashes with ModuleNotFoundError for pandas. What command resolves this?
  • NumPy performs matrix multiplication faster than a pure Python loop. Explain why, given that both run on the same CPU.