Anatomy of a Python file
Python is an interpreted, high-level, general-purpose programming language emphasizing code readability.
File extensions: .py
Every part of the example below is labelled and explained. This page is one of 55 annotated tours on AnatomyOf, a free, open-source project by LunarWerx Studios.
What is inside a Python file
Shebang
Specifies the interpreter path (optional, for Unix-like systems).
The shebang (#!) must be the very first bytes of the file. On Unix-like systems the kernel reads it to find which interpreter runs the script. /usr/bin/env python3 asks env to locate python3 on the current PATH, which is more portable than hard-coding a path like /usr/bin/python3. Windows ignores the shebang (though the py.exe launcher can read it), and it is entirely optional when you invoke the script explicitly with python script.py. It only matters when the file is executed directly, e.g. ./script.py after chmod +x.
Docstring
Module, class, or function documentation in triple quotes.
A string literal placed as the first statement of a module, class, or function becomes its docstring: it is stored at runtime in the __doc__ attribute and shown by help(). Triple quotes (""") let it span multiple lines. Convention (PEP 257): a one-line summary, then a blank line, then details. Tools like Sphinx, pydoc, and IDE tooltips surface docstrings as documentation, so they are worth writing well.
Import statements
Imports external modules or functions.
import os binds the whole module to a name, while from datetime import datetime pulls a single attribute into the current namespace. Imported modules are cached in sys.modules, so importing the same module twice is cheap. Style (PEP 8): imports live at the top of the file, grouped as standard library, third-party, then local imports: one blank line between groups.
Variable definition
Assigns a value to a name.
Assignment (=) binds a name to an object. Names carry no declared type. A module-level name written in ALL_CAPS signals a constant by convention only; Python does not enforce immutability, it is a contract between programmers. Type hints such as GLOBAL_CONSTANT: int = 42 make intent explicit and let static checkers like mypy or pyright verify usage without changing runtime behavior.
Class definition
Defines a blueprint for objects using class.
class creates a new type. Methods are functions defined in the class body whose first parameter (self) receives the instance. __init__ runs right after an object is created and typically assigns instance attributes like self.name. Python also supports inheritance (class Child(Parent):), multiple inheritance, and "dunder" protocol methods like __repr__ and __eq__ that hook instances into built-in behavior.
Function/method definition
Defines a reusable block of code using def.
def binds a function object to a name. The body is indented. Whitespace is the block syntax in Python. Functions accept positional and keyword arguments, defaults, and *args/**kwargs, and return None unless a return statement says otherwise. The same syntax inside a class body defines a method; the instance arrives as the first parameter, conventionally named self. f-strings like f"Hello, {self.name}!" interpolate expressions directly into string literals.
Control flow (conditional)
Executes code based on a condition (if, elif, else).
if/elif/else route execution based on truthiness: empty containers, 0, None, and "" all count as false. Conditions need no surrounding parentheses, and comparisons chain naturally (0 < x < 10). Since Python 3.10, structural pattern matching (match/case) covers the multi-branch cases a switch statement would handle in other languages.
Control flow (loop)
Repeats code (for, while).
for iterates over any iterable (lists, strings, dicts, generators, or range(...)) rather than counting indices; while repeats as long as a condition holds. break exits early, continue skips to the next pass, and a loop's optional else clause runs only when it finishes without break. range(3) yields 0, 1, 2. The stop value is exclusive. Use enumerate(items) when you need the index alongside each element.
Main execution block
Ensures code runs only when executed as a script.
Every module has a __name__ variable: it equals "__main__" when the file is executed directly, but the module's own name when imported. Guarding the entry point this way lets one file serve as both a runnable script and an importable library without side effects at import time. The guard also matters on Windows for multiprocessing, which re-imports the main module in child processes and would otherwise re-run top-level code.
Official Python site · All languages on AnatomyOf
The interactive tour needs JavaScript. Enable it to hover a callout and trace it into the code.