On this page
  1. codeop
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Preserving __future__ Imports Across REPL Inputs
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

codeop

Prev: codecs | Up: stdlib_module | Next: collections
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — codeop
Tags: #public #python3 #stdlib


Import

import codeop

Overview

Low-level compiler helper (compile_command(), Compile, CommandCompiler) backing code to determine whether a string of Python source is a complete statement, an incomplete multi-line block (returns None), or a syntax error (raises SyntaxError). Use codeop when building custom REPLs, notebook kernels, or interactive web consoles.

Quick Start

import codeop

assert codeop.compile_command("x = 1 + 2") is not None      # complete -> code object
assert codeop.compile_command("for i in range(3):") is None  # incomplete -> wait for more lines

Implementation Walkthrough

1. Preserving __future__ Imports Across REPL Inputs

A codeop.CommandCompiler instance remembers from __future__ import ... flags from earlier statements so subsequent lines compile with the same semantics:

import codeop

compiler = codeop.CommandCompiler()
assert compiler("from __future__ import annotations") is not None
assert compiler("def f(x: Node) -> Node: pass") is not None

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes