Skip to main content

How Python Works

Beginner Satellite

How Python Works

Python source files become bytecode that runs on a virtual machine. Understanding that flow helps you debug imports, performance, and packaging issues later.

Execution pipeline​

  1. Source code (.py) is read by the interpreter.
  2. Python compiles it to bytecode (.pyc files in __pycache__).
  3. Bytecode runs on the Python Virtual Machine (PVM).

This compilation step happens automatically; you don't manage it manually.

CPython vs others​

  • CPython: default implementation, written in C.
  • PyPy: JIT-compiled, faster for long-running programs.
  • MicroPython / CircuitPython: embedded devices.

The language spec stays consistent, but performance characteristics vary.

Import mechanism recap​

When you import module, Python:

  1. Checks sys.modules cache.
  2. Searches paths in sys.path.
  3. Loads source/bytecode and executes the module once.

Understanding this explains why top-level code runs on import and why circular imports cause issues.

Memory model​

  • Python uses reference counting with a cycle detector.
  • Objects live on the heap; names reference them.
  • gc module lets you inspect or tweak garbage collection behavior, but defaults suffice for most apps.

Next up in your learning path