devnotes.

Importing Modules and the Standard Library

Python's "batteries included" standard library provides a huge range of ready-to-use modules, accessed with import.

import math
print(math.sqrt(16))          # 4.0

from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)

import random as rnd            # alias to shorten a long or common name
print(rnd.choice(["heads", "tails"]))

from collections import Counter   # import a specific name directly
import os
print(os.getcwd())                 # current working directory

import module gives access to everything in that module through the module.name syntax; from module import name imports a specific name directly into the current file's namespace, letting you write name instead of module.name. import module as alias is common for long names (import numpy as np) or to avoid clashing with an existing name.

The standard library covers an enormous range of everyday needs without installing anything extra: math (mathematical functions), datetime (dates and times), random (randomization), os/pathlib (filesystem operations), json (JSON encoding/decoding), re (regular expressions), collections (specialized container types), and many more — always check whether the standard library already solves a problem before reaching for a third-party package.

Avoid from module import * (importing everything into the current namespace) in real code — it makes it unclear where a given name actually came from, and risks silently overwriting existing names, one of the more common sources of confusing bugs in beginner code.

Importing Modules and the Python Standard Library | DevNotes