Modules, Packages & the Standard Library
You'll learn to
- -Import a module or specific names from it with `import` and `from ... import ...`
- -Understand what a package is, at a glance
- -Recognize a handful of genuinely useful standard library modules you will use constantly
Every `.py` file is a module, and Python's standard library ships with dozens of them ready to import - no installation required. Knowing what is already available saves you from reinventing solved problems, and it matters immediately: the Forge Algorithm Lab's code sandbox allows importing a specific, safe allowlist of standard library modules, and several of the most useful ones are introduced right here.
import and from ... import ...
`import math` brings in the whole module, and you access its contents with a `math.` prefix. `from math import sqrt, pi` brings specific names directly into your file's namespace, so you use them unprefixed. Both are correct; `from ... import ...` is more concise for a few specific names, while `import module_name` is clearer about where a name came from when a file uses many different modules.
What a Package Is, at a Glance
A package is just a directory of modules, typically marked with an `__init__.py` file so Python recognizes it as an importable unit. You do not need to build your own packages for Forge Algorithm Lab work - single-file submissions are the norm there - but recognizing `import numpy` or `from collections import Counter` as "importing a package" versus "importing a module" is useful vocabulary for reading other people's code.
A Few Genuinely Useful Standard Library Modules
These four come up constantly in everyday Python, and not by coincidence - they are also exactly the kind of modules the Forge Algorithm Lab's sandboxed code runner allows you to import (alongside a few others like `functools`, `heapq`, and `bisect` that later chapters and the Algorithms phase will introduce).
- -`math`: numeric operations beyond the basic operators - `sqrt`, `floor`, `ceil`, `factorial`, and more.
- -`random`: pseudo-random number generation - `randint`, `choice`, `shuffle`.
- -`collections`: extra container types - `Counter` for tallying, `defaultdict` for auto-initializing missing keys, and more you will meet later.
- -`itertools`: building blocks for combining and iterating over sequences efficiently - `combinations`, `permutations`, `chain`, and others.
The Forge Algorithm Lab's code sandbox restricts what you can import, for security - it does not run arbitrary code with unrestricted system access. The modules above are all on that allowlist, so patterns you practice here will work directly in lab submissions.