Advanced Python / Start here

Check readiness and interpreter build

Lesson 1 of 42. Open to read. No account needed.

Start with evidence you can explain

An unfamiliar traceback is harder to diagnose when the terminal is running a different Python from the one you intended. Establish the interpreter first, then check the starting abilities the advanced lessons will build on.

By the end, you should be able to identify the executable and build you ran, explain a small function/class/file program, change its behavior deliberately, and locate a supplied failure. Successful output is one piece of evidence; your explanation and independent change matter too.

This walkthrough uses macOS ARM64 and zsh, with final CPython 3.15.1, standard GIL-enabled build. CPython is an implementation of Python; the version identifies its release. A build is the executable produced with a particular set of build options. Linux and Windows command routes have not been checked for this course. A matching interpreter report on another OS does not establish a checked walkthrough there.

You need an editor that saves plain UTF-8 text, a terminal, permission to use the selected interpreter, and the starting abilities below. All example code is supplied here. The exercise creates one disposable directory and a small text note. Package environments and dependency installation come in lesson 2.

Starting abilityEvidence in this lesson
P01: functions, conditions and loopsExplain which names pass the condition; change the threshold
P02: collections and stringsDistinguish the tuple, dictionary, result list and set count
P03: named exceptions and tracebacksExplain the handled ValueError and locate an uncaught key lookup
P04: a simple class and importsIdentify the imported Path and the ArchiveNote instance/method
P05: paths and UTF-8 filesInspect the note written and read by the program
P06: editor and terminalSave the two files and run them from the declared directory

Select the executable deliberately

Use an existing interpreter approved for your machine. If it is missing, use the official 3.15.1 release page and its macOS installation guidance, or ask your administrator for that specific release/build. The installer can place software in shared system locations, so obtain the permission your machine requires. Do not replace an OS-managed Python to complete this exercise.

These paths describe different acquisition routes; they are not interchangeable strings to copy without checking:

The author-tested Homebrew installation on ARM64 uses /opt/homebrew/bin/python3.15.

For the standard python.org framework, the documented candidate is /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15.

The official framework installer route was not installed or walked through during this lesson's author check. Its documentation describes standard and free-threaded frameworks coexisting. Select the intended executable and inspect it rather than inferring its build from the command name.

In zsh, set AP_PYTHON to the absolute path of your approved executable. The following is the author-tested path. If yours differs, replace only the quoted path before running these commands:

AP_PYTHON='/opt/homebrew/bin/python3.15'
"$AP_PYTHON" -VV

AP_PYTHON is a shell variable, not a Python variable. Quoting its expansion keeps the executable path together. -VV prints version and build information and exits. It does not install anything. Retain this information; the compiler name and build timestamp can differ between distributions of the same release. If the path is missing or the release differs, resolve that before continuing. Keep this terminal open so the variable remains available.

Create one disposable workspace

Declare this directory to be owned by this exercise before creating any files. From your current zsh terminal, run:

AP_LESSON_ROOT="$(mktemp -d -t advanced-python-readiness)"
printf '%s\n' 'advanced-python:lesson-1' > "$AP_LESSON_ROOT/.advanced-python-owner"
cd "$AP_LESSON_ROOT"
pwd

On macOS, mktemp -d -t creates a fresh directory with the given prefix. $(...) captures its printed path in AP_LESSON_ROOT. The marker records the exercise identity. cd makes this the working directory; relative file paths below refer to it. Save the exact pwd output for recovery. The random suffix and temporary parent path will vary. If directory creation or cd fails, stop and inspect that failure before saving or deleting any files.

Use your editor to save runtime_check.py and readiness.py in this directory as plain UTF-8 text. Copy each complete Python block below, without the Markdown fences. No repository checkout or practice-file download is required.

Read the running interpreter

The GIL, or global interpreter lock, affects how a CPython process executes Python code across threads. Its presence does not make a program's shared state safe. We will investigate synchronization later.

Two facts must be kept separate: whether this executable was built with free-threading support, and whether the GIL is enabled in this process now. A free-threaded build can run with its GIL enabled. An extension import can also change the GIL state in such a build. This course starts with the standard build; gil_enabled: True alone is insufficient to identify it.

Save this complete file as runtime_check.py:

import sys
import sysconfig

print("implementation:", sys.implementation.name)
print("version:", sys.version_info[:3], sys.version_info.releaselevel)
print("executable:", sys.executable)

if (
    sys.implementation.name != "cpython"
    or sys.version_info[:3] != (3, 15, 1)
    or sys.version_info.releaselevel != "final"
):
    raise SystemExit("STOP: select the course's final CPython 3.15.1 executable.")

free_threaded_build = sys.abi_info.free_threaded
gil_enabled = sys._is_gil_enabled()
print("free_threaded_build:", free_threaded_build)
print("Py_GIL_DISABLED:", sysconfig.get_config_var("Py_GIL_DISABLED"))
print("gil_enabled:", gil_enabled)

if free_threaded_build or not gil_enabled:
    raise SystemExit("STOP: select the standard GIL-enabled build for this course.")

print("baseline: matched")

The first block reports the implementation, release and actual executable. The slice [:3] selects major, minor and micro version components. The check also requires a final release; a prerelease with the same three numbers does not pass. SystemExit stops the script unsuccessfully with the stated message. The version check precedes APIs specific to the selected runtime.

For CPython 3.15, sys.abi_info.free_threaded reports the build capability. sys._is_gil_enabled() reports the running process state; this documented CPython API is not guaranteed in other implementations. The script records both and rejects a free-threaded build even when its GIL is currently enabled.

sysconfig.get_config_var() reads a build configuration value. For Py_GIL_DISABLED, 1 identifies free-threading support. The author-tested standard build reports 0. A missing configuration variable returns None; do not treat that as an independently established build fact. The script's build decision uses sys.abi_info.free_threaded, not a guess about None.

From the marked workspace, run:

"$AP_PYTHON" runtime_check.py

Illustrative output, with the path shortened for display:

implementation: cpython
version: (3, 15, 1) final
executable: /.../python3.15
free_threaded_build: False
Py_GIL_DISABLED: 0
gil_enabled: True
baseline: matched

Inspect your real executable path rather than typing the shortened one. The final line means the script's interpreter/build criteria matched. It does not verify package versions, the executable's authenticity or your Python fluency. Keep your approved acquisition route and actual report together.

ObservationInterpretation and next step
Another implementation, version or prereleaseSelect the approved final CPython 3.15.1 executable
Free-threaded build True, GIL FalseDifferent build and runtime state from this course baseline
Free-threaded build True, GIL TrueGIL is enabled now, but this is still the other build; select the standard executable
Free-threaded build False, GIL TrueThe build/state pair expected here, subject to the version check
Missing expected API after the version checkInspect executable/distribution details; do not invent a successful report

Run the readiness program only after baseline: matched. Otherwise resolve the differing report and rerun the interpreter check first.

Check the starting abilities with a real file

Read this program before running it. Predict which names are selected and what the note will contain. Save it as readiness.py:

from pathlib import Path

owner = Path(".advanced-python-owner")
if not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-1":
    raise SystemExit("STOP: run inside the marked lesson-1 workspace.")


def choose_names(names, minimum):
    selected = []
    for name in names:
        if len(name) >= minimum:
            selected.append(name.upper())
    return selected


class ArchiveNote:
    def __init__(self, label):
        self.label = label

    def render(self, names):
        return self.label + ": " + ", ".join(names)


names = ("oak", "cedar", "ash", "oak")
rules = {"minimum": 4}
selected = choose_names(names, rules["minimum"])
note = ArchiveNote("Chosen")
text = note.render(selected)

note_path = Path("readiness-note.txt")
note_path.write_text(text + "\n", encoding="utf-8")
loaded = note_path.read_text(encoding="utf-8")
print(loaded, end="")
print("unique selected names:", len(set(selected)))

try:
    int("not-a-count")
except ValueError as error:
    print("handled:", type(error).__name__)

print("readiness: finished")

The marker check catches an ordinary wrong-directory mistake before the note is written. The or stops after a missing marker, so the following read is not attempted in that case. This is an exercise ownership check, not a sandbox for untrusted files.

choose_names takes a sequence and threshold, builds a result list, and returns uppercase names whose lengths meet >= minimum. The tuple preserves the input order and duplicates; the dictionary supplies the threshold by its exact key. With minimum four, only cedar qualifies. Changing the dictionary value changes the condition's result without changing the function body.

ArchiveNote("Chosen") creates an instance. Its initializer stores the label on self; calling note.render(selected) uses that instance and joins the selected names into one string. This checks basic class/method knowledge; descriptor and binding details come later.

Path("readiness-note.txt") names a file relative to the working directory. write_text writes the string with a final newline, replacing this exercise's previous note on a rerun. read_text reads the contents back with the same explicit encoding. print(..., end="") avoids adding a second newline. set(selected) is used only to count distinct selected names; it does not replace the ordered result list.

The named ValueError handler covers only the attempted conversion of "not-a-count" to an integer. The program reports its class and continues. It does not catch every error elsewhere in the file.

Run from the marked workspace:

"$AP_PYTHON" readiness.py
cat readiness-note.txt

Illustrative program output:

Chosen: CEDAR
unique selected names: 1
handled: ValueError
readiness: finished

The separate cat command displays the actual saved note: Chosen: CEDAR. Compare the file contents, selected-name reasoning and final completion line. Running the unchanged file again should rewrite the same note, not append a second result. Merely obtaining the supplied output by copying the program does not demonstrate the readiness abilities.

Diagnose a traceback and stale output

Make one deliberate fault at the call site in readiness.py. This is an excerpt replacing that single line, not another complete program:

selected = choose_names(names, rules["mininum"])

Run readiness.py again. The dictionary contains minimum, so looking up the misspelled key raises an uncaught KeyError. Its traceback identifies the file, line and operation; the final line is illustratively:

KeyError: 'mininum'

Locate the failing lookup yourself, compare it with the dictionary's actual key, repair the call, and rerun. This is different from the later handled ValueError: the lookup fails before the file-writing block and outside that handler. A note from the last successful run can still exist. Its presence does not prove the failed run reached the writing or completion steps.

Check Your Understanding

Attempt these tasks before opening the reasoning. Record your prediction and explanation, then compare them with actual behavior.

  1. In the repaired program, change only the minimum from four to three. Predict the ordered note and distinct-name count. Run it and inspect the note. Explain the role of all four collections used by the program.
  2. Next use an empty input tuple. Predict whether the loop, file-writing block and named exception handler still execute. Verify your prediction, then restore the original tuple and minimum four.
  3. A candidate reports CPython 3.15.1 final, free_threaded_build: True and gil_enabled: True. Does it match this course baseline? Explain the two different facts rather than changing interpreter settings to obtain a pass.
  4. Identify the line that imports Path, the instance creation, the file path versus file contents, and the key lookup that failed earlier. If you cannot explain several of these, decide what introductory study you need first.

Answer and Reasoning

Hint 1: separate the stages

Trace each original name through the condition before considering the class or file. For the interpreter report, ask what describes the executable and what describes the current process.

Hint 2: count without replacing the result

Both occurrences of oak pass a threshold of three. The result list retains them; the set used by len counts distinct values. An empty tuple skips the loop body, not the later statements.

Compare with the results

With minimum three the note is Chosen: OAK, CEDAR, ASH, OAK and the distinct count is three. The tuple is the ordered input, the dictionary maps the threshold key to its value, the list is the selected ordered result, and the temporary set supplies the distinct count. Replacing the result with that set would lose duplicate and ordering information.

With names = (), the function returns an empty list. The note contains Chosen: followed by a newline and the distinct count is zero. File writing and the deliberately handled ValueError still occur. There is no requirement to change unrelated class or exception code to handle an empty input.

The candidate with both build capability and current GIL state True fails this baseline. The GIL being on now does not turn a free-threaded build into the standard build. Select the approved standard executable; do not rewrite the report or weaken its conditions.

from pathlib import Path supplies the path class. ArchiveNote("Chosen") creates the instance; note_path names a file while loaded contains its text. rules["mininum"] raised the earlier KeyError because that key was absent. Repairing the key preserves the intended program instead of adding a handler that hides the mistake.

Decide whether to continue

Continue when the interpreter/build report matches and you can explain P01–P06, make the threshold/empty-input changes, inspect the real note and repair the lookup. These are self-checks, not an independently graded skill assessment.

For one small gap, revisit the relevant block explanation and repeat the variation. A function's arguments become its local inputs; its returned list becomes selected. An instance keeps its label in self.label. A relative path names a location; reading that path returns contents. A named exception handler applies to its own try block. If several of these ideas are unfamiliar, complete introductory Python work and repeat the readiness task before the advanced core. No particular paid course is required.

Reset and cleanup

For an ordinary rerun, restore the supplied source and keep the same marked workspace. If execution stopped partway, inspect the traceback and current file inventory; a missing or old note is not a reason to change permissions or delete an unrelated directory. You can instead create a new workspace with the earlier mktemp commands and recreate the two supplied files.

If the terminal was closed, recover AP_LESSON_ROOT from the exact path you saved and select AP_PYTHON again. Do not find a directory by a broad wildcard.

After recording any evidence you want to keep, return to the exact root and inspect it:

cd "$AP_LESSON_ROOT"
pwd
cat .advanced-python-owner
ls -a

Stop if cd fails, the path is not your recorded root, or the marker is not advanced-python:lesson-1. The expected exercise files are the marker, runtime_check.py, readiness.py and readiness-note.txt. Inspect unexpected files before deletion and move any evidence you want to keep elsewhere. Only after confirming ownership and inventory, remove those exact files:

rm runtime_check.py readiness.py readiness-note.txt .advanced-python-owner
cd ..
rmdir "$AP_LESSON_ROOT"

If an interrupted attempt never created the note, omit that absent filename from rm after inspecting the inventory. rmdir removes an empty directory; an unexpected remaining file makes it refuse rather than recursively deleting it. The selected interpreter remains installed. The next lesson creates its own environment from the interpreter identity you recorded here.

References

Revisit this lesson through Revision or Quick Reference. They share the same lesson and readiness boundary.

37 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy