Skip to content

Module 16 · External Libraries and APIs — topic 1 of 12

External libraries

What third-party libraries are, why Python's ecosystem is so valuable, how to choose a trustworthy library, and how to write code that adapts when an optional library is missing.

Beginner 8 min read·Lesson 235 of 306 in Python Programming

Learning objectives

  • Explain what external libraries provide
  • Evaluate whether a library is a good choice
  • Write code that degrades gracefully without an optional library

Definition

An external (third-party) library is a package written by someone other than the Python core team, usually published on PyPI and installed with pip. Libraries add capabilities such as numerical computing, data analysis, plotting, web requests and machine learning.

Introduction

Python's popularity comes largely from its ecosystem: NumPy for numbers, pandas for tables, Matplotlib for charts, requests for the web, and hundreds of thousands more.

Why it matters

Using a mature library can replace weeks of work with a few lines — but every dependency also needs installing, updating and trusting.

Detailed explanation

External libraries are installed per environment with pip and imported like any module. The import name sometimes differs from the install name (pip install scikit-learn → import sklearn).

The scientific stack — NumPy, pandas, Matplotlib, SciPy and scikit-learn — is the foundation of data science in Python. requests, httpx and FastAPI cover the web.

Before adopting a library, check that it is actively maintained, well documented, widely used, has a compatible licence and supports your Python version.

Prefer the standard library for small tasks: a dependency for something csv or json already does adds risk without benefit.

Optional dependencies can be imported inside try/except ImportError, falling back to a slower or simpler implementation.

Libraries change over time. Pin versions in requirements.txt and read release notes before upgrading.

The following lessons introduce NumPy, pandas, Matplotlib and requests, and show how to call web APIs with the standard library too.

Syntax

Python
# install once (in a terminal)
# python -m pip install numpy
import numpy as np
print(np.array([1, 2, 3]) * 2)
  • Install with pip, then import.
  • Check maintenance and licences.
  • Prefer the standard library for small tasks.

Code examples

Using an external library

Python
import numpy as np
a = np.array([1, 2, 3, 4])
print(a * 10, a + a, a.mean())
print(a.dtype, a.shape)
Output
[10 20 30 40] [2 4 6 8] 2.5
int64 (4,)

Requires NumPy (python -m pip install numpy). The integer type can be int32 on some older Windows builds.

Checking for an installed distribution

Python
from importlib.metadata import PackageNotFoundError, version
try:
print(version("definitely-not-installed-demo"))
except PackageNotFoundError:
print("definitely-not-installed-demo is not installed")
Output
definitely-not-installed-demo is not installed

More examples

Using a library when it is available

Python
def summarize(values):
try:
import numpy as np
except ImportError:
n = len(values)
mean = sum(values) / n
var = sum((v - mean) ** 2 for v in values) / n
return {"mean": mean, "std": round(var ** 0.5, 3), "engine": "pure python"}
arr = np.array(values, dtype=float)
return {"mean": float(arr.mean()), "std": round(float(arr.std()), 3), "engine": "numpy"}
result = summarize([4, 8, 15, 16, 23, 42])
print(result["mean"], result["std"])
print(result["engine"] in ("numpy", "pure python"))
Output
18.0 12.315
True

Step-by-step explanation

  • The function tries to import NumPy only when it is called.
  • With NumPy installed it uses fast array operations; without it, a pure-Python fallback computes the same population standard deviation.
  • Either way the results are identical, so the rest of the program doesn't care which engine ran.

Expected output

Running “Using a library when it is available” prints exactly:

TextOutput
18.0 12.315
True

Practical applications

  • Data analysis notebooks built on pandas and Matplotlib.
  • Web back ends built on FastAPI or Django.

Best practices

  • Choose well-maintained, widely used libraries.
  • Pin versions for applications.
  • Isolate dependencies in a virtual environment.

Common mistakes

A dependency for a one-liner

Avoid

pip install some-tiny-package # to pad a string

Prefer

text.rjust(10)

Each dependency is code you must trust and update; use built-ins when they suffice.

Important notes

  • Some libraries include compiled code; pip downloads ready-built 'wheels' for common platforms.

Key takeaways

  • External libraries extend Python far beyond the standard library.
  • Evaluate maintenance, popularity and licence before adopting.
  • Optional imports can fall back gracefully.

Try it yourself

  1. 1
    Pick a PyPI package and record its latest version, licence and last release date.
  2. 2
    Write a function that uses rich for coloured output if installed and plain print otherwise.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.