Python Master Course V2 — 063. Python Standard Library
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 — MODULES AND PACKAGES · LESSON 063 / 200
Python Standard Library
Estimated study: 60–90 minutes. Prerequisites: functions, collections, control flow and the preceding lesson. Level: intermediate Python.
Video lesson
Video not yet available. Reserved for a verified video URL/player; written learning materials are available now.
Learning outcomes
Select standard-library modules before dependencies. After completing this lesson, you should be able to explain the underlying mechanism, run the example, identify a boundary case, and apply the concept in a practical program.
Understand and apply: Python Standard Library
Distinguish three sources of functionality
Built-in functions and types such as len, sum, list, and dict are available without importing a module. The standard library is the collection of modules distributed with Python, including collections, pathlib, statistics, json, and decimal. These usually require an import before use. Third-party packages come from outside that library and need a separate dependency decision and installation workflow. Standard-library does not mean every operation is a built-in name.
Before choosing a dependency, describe the task and check whether a standard-library tool meets it. Use collections.Counter for counting hashable values, pathlib for path operations, statistics for common numerical summaries, csv and json for their respective data formats, and datetime for date/time objects. Familiar tools reduce custom code, but they do not automatically validate your application’s records, protect every filesystem operation, or choose your business rules.
Count categories without losing multiplicity
Python code
from collections import Counter
statuses = ["ready", "waiting", "ready", "ready"]
counts = Counter(statuses)
print(counts["ready"])
print(counts["missing"])
print(sorted(counts.items()))
Expected output
3
0
[('ready', 3), ('waiting', 1)]
Counter retains how many times each value appears, unlike a set that keeps only distinct members. Looking up a missing key returns zero without inserting that key, so missing does not appear in the printed items. Sorting the items gives a predictable alphabetic presentation. Counter also offers most_common, but decide how ties should appear rather than assuming alphabetical tie-breaking; equal-count results preserve first-encounter order.
Construct paths without pretending files exist
Python code
from pathlib import Path
report = Path("reports") / "today.csv"
print(report.name)
print(report.suffix)
print(report.as_posix())
Expected output
today.csv
.csv
reports/today.csv
The slash operator joins path components. Creating a Path object does not create a directory or file; it describes a path. Name and suffix inspect its components without opening the target. A direct print of Path uses the platform’s native representation, which may contain backslashes on Windows. The explicit as_posix call uses forward slashes for the stable display shown here. It is a formatting choice, not proof that the target exists.
Combine two modules into a filename report
Python code
from collections import Counter
from pathlib import Path
def count_extensions(names):
if not isinstance(names, list):
raise TypeError("names must be a list")
counts = Counter()
for name in names:
if not isinstance(name, str) or not name.strip():
raise ValueError("each filename must be a nonempty string")
extension = Path(name).suffix.casefold() or "[none]"
counts[extension] += 1
return counts
filenames = ["reports/A.CSV", "notes.txt", "reports/B.csv", "README"]
for extension, count in sorted(count_extensions(filenames).items()):
print(extension, count)
print(dict(count_extensions([])))
Expected output
.csv 2
.txt 1
[none] 1
{}
The input is a list of filename strings, not a directory to scan. Each name becomes a Path, its final suffix is casefolded for case-insensitive grouping, and a name without a suffix enters the explicit none category. An empty list is valid and returns an empty Counter. The function does not verify real files or infer their contents from extensions. A file named data.csv might contain something entirely different.
Test an uppercase suffix, no suffix, repeated categories, empty input, and an invalid blank name. A name such as backup.tar.gz contributes only .gz because suffix means the final component; suffixes provides a list when an application needs a compound extension policy. Choose one policy and document it. Later lessons cover real directory traversal and format parsing; this report deliberately practices library selection and composition without reading or writing files.
Runnable Python example
Requires Python 3.10+. Save the example as lesson63.py and run python lesson63.py (or python3). If it writes a file, run it in a disposable practice directory.
from collections import Counter
from pathlib import Path
print(Counter(['a','b','a'])['a'])
print((Path('reports') / 'today.csv').as_posix())
Expected output:
2
reports/today.csv
Step-by-step walkthrough
Read each statement in execution order. Identify imported modules, assigned variables, functions and the result passed to print(). Compare the output with the expected output and then change one input. Explain why the behavior changed. When an exception occurs, read the final traceback line and inspect the call that produced it.
Extension example
Refactor the central calculation or operation into a named function with a docstring and type hints. Add a caller that invokes it twice with different inputs. Test both results with assertions; for file operations, also test that the expected file exists and clean up practice files afterward.
Guided project — Python Standard Library application
Build a report summarizer using collections and pathlib.
- Write a short requirements document specifying input data, output data and expected errors.
- Implement one focused function or module for the core behavior.
- Write a separate program entry point to collect or construct example input.
- Add validation and informative errors where appropriate.
- Test a normal case, a boundary case and an invalid case.
- Write a README showing how to run and test the program.
Acceptance criteria: clear behavior, no unexplained dependencies, reproducible execution and a documented result. The project is a guided assignment; its implementation must be completed and tested by the learner.
Common mistakes, debugging and best practices
- Importing a local file with the same name as a standard-library module, causing shadowing.
- Using broad exception handlers that conceal the real defect.
- Assuming a path or dependency exists on every computer.
- Mixing input/output and reusable business logic into one difficult-to-test function.
- Testing only the happy path rather than edge cases and failures.
Debugging procedure: reproduce the failure with the smallest input; read the traceback; verify assumptions and data types; change one thing; rerun the same test; add a regression test after the fix.
Practice and explained answers
Try each question before opening its answer. These self-checks do not record course completion.
1. Is len a standard-library module that must be imported?
Need a hint?
Distinguish names available immediately from names imported from a module.
Reveal answer and explanation
Answer and reasoning: No. Len is a built-in function available directly. Counter belongs to the collections standard-library module and must be imported or accessed through an imported collections module. Third-party packages are a separate category.
2. What is the difference between Counter(["a", "a", "b"]) and set(["a", "a", "b"])?
Reveal answer and explanation
Answer and reasoning: The Counter retains counts of two for a and one for b. The set records only that a and b occur. Use Counter when multiplicity matters, such as counting report categories.
3. Does Path("reports") / "today.csv" create a file?
Reveal answer and explanation
Answer and reasoning: No. It constructs a path object. Filesystem creation requires a separate operation such as opening a file for writing, and directories likewise need deliberate creation. Constructing a path does not establish existence or permissions.
4. Why print report.as_posix() rather than report for an exact cross-platform output example?
Reveal answer and explanation
Answer and reasoning: A direct Path string uses platform-specific separators. As_posix explicitly requests forward slashes, so the relative example displays reports/today.csv consistently. That representation does not change the actual filesystem or guarantee the path is valid there.
5. How would backup.tar.gz be classified by count_extensions, and what would changing that rule require?
Reveal answer and explanation
Answer and reasoning: It contributes to .gz because Path.suffix returns the final suffix. To group compound extensions such as .tar.gz, use an explicit policy based on suffixes or recognized combinations, then update examples and tests. Do not silently change categories after reports depend on them.
Mastery checkpoint and summary
Demonstrate the concept without copying, explain one failure mode, complete the guided project and write three independent tests. These are suggested mastery checks, not account-synchronized completion records.
Key takeaway: Select standard-library modules before dependencies. Apply it through clear contracts, thoughtful error handling, and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.