Every Python developer knows the pain. The stock python prompt gives you no syntax highlighting, no real multiline editing, and a Control-C that can wipe out half-finished state. Dropping into a debugger inside a running service, you cannot bolt a heavyweight shell onto it either: the embed point must stay small, must not fight the host’s event loop, and must not lose history when the process dies. IPython covers some of this but drags a large dependency tree, and its embed assumptions do not always fit a foreign asyncio loop.
ptpython is the middle path. Version 3.0.32 ships roughly twenty modules under src/ptpython/, builds everything on prompt_toolkit, and depends on only appdirs, jedi, prompt_toolkit and pygments (see pyproject.toml, lines 20-26). The whole project is a read-eval-print skeleton wrapped around one prompt_toolkit Application: the loop is repl.py, the input side is python_input.py, and the smarts live in completer.py and signatures.py.
The source is worth reading for its threading discipline: a dedicated document, docs/concurrency-challenges.rst, explains why the prompt UI runs in a background thread while eval stays on the caller’s thread — and what breaks if you get it wrong. This tour walks the real files, line numbers checked against main.
ptpython at a glance: two console entry points feed embed(), which drives a PythonRepl subclass over the PythonInput application object; completion, signatures, layout and printing hang off that one central object.
Reading the overview from left to right:
PythonRepl, L84 — the loop class, a thin subclass ofPythonInputthat adds eval, await and exit semantics.eval, L294 — compile the line inevalmode first; onSyntaxErrorfall back toexec; a leading!becomesos.system(L303).run_and_show_expression_async, L192 — the async variant wiresloop.add_signal_handler(signal.SIGINT, ...)at L211 so Control-C cancels the eval task instead of killing the loop._store_eval_result, L373 — writes the result into locals as_and_{statement_index}, exactly like the standard REPL.PythonInput.read, L1074 — runs the prompt UI within_thread=True(L1100), dodging Python’s ban on nested event loops.PythonCompleter, L43 — one dispatcher over system, dictionary, path-in-string and Jedi completers.DictionaryCompleter, L302 — eval-based dict-key and list-index completion, guarded by regexes that only match attribute and item lookups.OutputPrinter, L35 — dataclass that renders reprs with optional black reformatting, pygments highlighting, filtered tracebacks and a--MORE--pager.
The detail view: 29 nodes across five groups, including the completer stack, the signature executor and the pager that lives inside the printer.
The loop: eval first, exec second, await everywhere
PythonRepl.eval implements a subtle trick. It compiles the input in eval mode and, only if that raises SyntaxError, recompiles in exec mode — deliberately outside the except block, so sys.exc_info() still reports the original error (the comment cites issue #435). Before any of that, a leading ! hands the line to os.system, which is why the completer and lexer both special-case ! input elsewhere.
Top-level await is handled through compiler flags rather than parsing. get_compiler_flags in python_input.py (L450) scans the user’s globals for __future__._Feature instances and ORs their flags into every compile call, while PythonRepl.get_compiler_flags (L377) adds PyCF_ALLOW_TOP_LEVEL_AWAIT when the interpreter supports it. After execution, _has_coroutine_flag (L76) checks the compiled code object’s co_flags against the COROUTINE flag it looked up from COMPILER_FLAG_NAMES in dis — a neat way of asking CPython whether the expression produced a coroutine. If it did, the blocking path drives it with loop.run_until_complete and the async path simply awaits it.
Interruption is the hard part. In run_and_show_expression_async, the eval runs as an asyncio.create_task, a SIGINT handler cancels that task directly, and a nested SystemExit is captured into a local variable so it cannot propagate out of create_task and kill the event loop (L200-215). The blocking path wraps the whole loop in a try/except for KeyboardInterrupt, so Ctrl-C during a slow repr lands in _handle_keyboard_interrupt (L401) and prints KeyboardInterrupt instead of unwinding the session.
Even exiting is engineered. The exit class (L495) is a sentinel: evaluating bare exit returns an object whose repr reads “Use exit() or Ctrl-D (i.e. EOF) to exit”, and run_and_show_expression turns that into ReplExit. Using _sitebuiltins.Quitter instead would close sys.stdin — fatal for an embedded shell that must return control to its host.
Completion: four completers behind one TAB
PythonCompleter routes by context. Input starting with ! goes to a SystemCompleter (L157-164). Text inside a string literal goes to a GrammarCompleter built from a regex grammar that recognizes quoted strings and skips comments (L91-130) — compiled lazily on first use and cached in _path_completer_grammar_cache, because building it costs startup time. Everything else reaches JediCompleter.
The Jedi path wraps jedi.Interpreter over the live namespaces via get_jedi_script_from_document (utils.py, L60). Its exception handling is a museum of real-world breakage: TypeError from bad syntax, UnicodeDecodeError on OpenBSD, AttributeError and KeyError from old jedi bugs, plus OSError, AssertionError, SystemError and NotImplementedError, each with a linked issue (L229-264). Completions are then sorted so parameters come first, underscore-prefixed names last (L267-277), and functions get a () suffix while parameters get ....
DictionaryCompleter is the boldest piece: it actually calls eval on fragments of your input to complete dictionary keys and list indices. Safety comes from the regex at L325-349, which only matches bare names followed by attribute dots and bracket lookups — no operators, no calls. It also parses for x in expr: loops (the for_loop_pattern, L354) and, if the iterable is a list or tuple, seeds the loop variable with its first element so completion works on iterators too. Meta-column reprs are computed lazily through a one-shot cache (meta_repr, L484); rendering thousands of menu entries cannot afford a repr per row.
The wrappers matter as much as the engines. HidePrivateCompleter (L620) caps upstream results with islice(..., 0, 5000) (L642) and applies three policies — never, always, or only-if-no-public — for underscore names. In python_input.py (L231-248) the whole stack is re-merged: a fuzzy branch is unioned with the normal completer using merge_completers(deduplicate=True), and the buffer runs it under a ThreadedCompleter (L949) so a slow jedi call never freezes typing.
Signatures without freezing the prompt
Signature hints run on a debounce. _on_input_timeout (python_input.py, L988) fires when the buffer text changes; a boolean guard _get_signatures_thread_running ensures only one lookup runs at a time, and the task re-runs in a loop until the buffer text stops changing (L1019-1028) — the classic “latest input wins” pattern. The lookup itself executes in an executor: first via jedi (get_signatures_using_jedi, signatures.py L163, which even pre-touches signatures[0].params to absorb a jedi crash on keyword-only args), and, if dictionary completion is on, via get_signatures_using_eval (L198).
That eval fallback is a small algorithm worth stealing: it walks backwards from the cursor with a bracket stack (paren_stack), counts top-level commas to identify the active parameter, and only then evals the expression left of the call to reach the callable (L206-249). Results normalize into a Signature built from jedi or inspect.signature; the first hit’s docstring goes into docstring_buffer (L1036-1041), rendered by signature_toolbar (layout.py, L234).
Output: reprs, black, and the MORE pager
OutputPrinter first honors the __pt_repr__ protocol (L151): prompt_toolkit objects can return rich formatted text instead of a plain string. It then decides whether the repr is displayable Python by literally calling compile() on it (L176-184); if it parses and the enable_output_formatting flag is on, the text is reformatted with black.format_str (L197-200), the same engine the black project ships as a library. A size gate protects you from pathological reprs: nothing above MAX_REFORMAT_SIZE = 1_000_000 (L31) is ever reformatted or highlighted.
Tracebacks get special treatment. _format_exception_output (L321) walks __cause__ and __context__ chains, trims the frame list at the first <stdin> frame so your embedded code’s frames disappear, and syntax-highlights the rest with PythonTracebackLexer. Long output goes through _print_paginated_formatted_text (L258): lines are soft-wrapped, painted a page at a time, and a --MORE-- toolbar — its own PromptSession running prompt(in_thread=True) — offers Enter, Space, a for print-all and q to abort (L381-397).
From readline-era hacks to a thread-based embed contract
The build facts tell the story:
- Input runs in a background thread by design:
read()callsself.app.run(pre_run=..., in_thread=True)(L1100), and the concurrency document states the eval must stay in the caller’s thread for Control-C and thread identity to work. - History is
ThreadedHistory(FileHistory(history_filename))(L254), loaded off-thread so big history files do not delay startup. - The F3 history browser (
history_browser.py) shows the lastHISTORY_COUNT = 2000entries (L65); you select lines with Space and Enter returns them as editable input. - Enter handling in
key_bindings.pyis aware of Python syntax:auto_newline(L310) copies indentation, removes one level after a line ending in ` pass`, and adds four spaces after a colon. - Validation compiles your input before accepting it (
validator.py, L24) and maps theSyntaxErrorrow/column back onto the buffer for an inline flag instead of a traceback. - The lexer (
lexer.py, L14) switches betweenBashLexerandPython3Lexerbased on the!prefix, so shell lines highlight correctly too. - Config resolution (
run_ptpython.py, L102) uses appdirs, honorsPTPYTHON_CONFIG_HOME, warns about the legacy~/.ptpythonlocation, andrun_config(repl.py, L453) executes yourconfig.pyand calls itsconfigure(repl)hook — the same hookembed()accepts as a parameter. - Two console scripts are registered in
pyproject.toml(L36-38):ptpythonandptipython. The latter imports IPython optionally and, throughptpython/ipython.py, subclasses IPython’sInteractiveShellEmbed(L223) so IPython sessions get ptpython’s editing UI without losing magics.
Vi users get first-class treatment: F4 toggles Emacs/Vi mode (key_bindings.py, L100), cursor shapes switch per mode via ModalCursorShapeConfig (python_input.py, L335), and read() captures the current vi input mode before each run and restores it afterwards (L1088-1095), so your navigation versus insert state survives across statements. The sidebar — three categories, Input, Display and Colors (python_input.py, L556-898) — exposes over twenty-five live options, including fuzzy completion, dictionary completion, color depth from monochrome to 24-bit, and brightness steps quantized to 1/20 increments (L595), with a swap_light_and_dark transformation for light-terminal users.
Honest Limits
- The dictionary completer really evaluates your code while you type. The sidebar option itself warns it is “potentially unsafe” (L674-679); a malicious
__getattr__runs just as it would at the prompt — a deliberate trade, default-off. - There is no multiprocessing safety story here — none is claimed. Isolation between your process and the REPL is your problem; the concurrency document covers threads and event loops only.
- Windows gets partial treatment:
loop.add_signal_handlerfor SIGINT does not exist on the Windows selector loop, andrun_asynccarries an XXX comment admittingKeyboardInterruptcan still land in the event loop selector (L282-285). - Jedi failures are swallowed silently — ten exception types return no completions rather than an error, keeping the prompt calm but hiding real bugs behind “no suggestions”.
- The eval-based signature fallback shares the dictionary completer’s eval behavior, so turning dictionary completion off also disables eval-based signatures (L1001-1004).
- IPython integration is a bridge, not a port: magics work through dedicated completer classes in
ipython.py, but features like IPython’s own display system are out of scope.
Enjoyed this post? Never miss out on future posts by following us