On this page
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
- Compiles only—does not execute:
compile_command()returns a code object; usecode.InteractiveConsoleif you want a full REPL loop. - Trailing newline matters for compound statements: A compound block like
if True:\n passis considered incomplete until terminated with a blank line ("\n").
Common Functions
- codeop.compile_command() —
compile_command(source, filename='<input>', symbol='single', flags=0)— Compile a command and determine whether it is incomplete.
Classes & Objects
- codeop.CommandCompiler — Instances of this class have call methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a future statement,
- codeop.Compile — Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts
Linked from
Related notes
- tuts/python3/stdlib_module/codecs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codeop/CommandCompiler Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codeop/Compile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codeop/compile_command Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/code Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib