Verbose example
actual ANSI capture from Pi · source: repo sample +
deterministic compare path
Use bash to run a verbose python syntax showcase from a heredoc with python3. Keep the transcript inline and normal.
$ python3 <<'PY'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Single-line comment
"""
Module docstring — should look different from regular strings.
Doctest inside:
>>> 1 + 1
2
"""
from __future__ import annotations
# ── Imports ───────────────────────────────────────────────────────────────
import asyncio
import keyword
import re
from typing import Final, Generic, Literal, Optional, TypeVar, Union, overload
# ── Runtime helpers ───────────────────────────────────────────────────────
x = 3.14159
data = b"abcdefgh"
command = {"action": "quit"}
items = {"one": 1, "two": 2}
matrix = [[1, 2], [3, 4]]
T = TypeVar("T")
type Vector = list[float]
# ── Numbers ───────────────────────────────────────────────────────────────
dec = 42
hex_ = 0xDEAD_BEEF
oct_ = 0o755
bin_ = 0b0010_0001
big = 1_000_000
flt = 3.14
sci = 6.626e-34
leading = .5
trailing = 5.
cmplx = 1.5 + 2j
# ── Strings ───────────────────────────────────────────────────────────────
plain = "double"
single = 'single'
raw = r"raw \n \t no-escape"
byt = b"\xff\x00"
uni = u"unicode prefix"
rb_ = rb"\xff literal"
escapes = "newline\n tab\t hex\x41 unicode\u0041 null\0 bell\a"
triple_d = """triple
double"""
triple_s = '''triple
single'''
raw_tri = r"""raw \t triple"""
f1 = f"simple {x}"
f2 = f"expr {1 + 1}"
f3 = f"repr {x!r} str {x!s} ascii {x!a}"
f4 = f"spec {x:.2f} {x:>10}"
f5 = f"debug {x = }"
f6 = f"nested {f'inner {x}'}"
f7 = rf"raw-f \n literal {x}"
impl = "one" " two" r" \three" f" {x}"
# ── Operators and collections ─────────────────────────────────────────────
arith = 1 + 2 - 3 * 4 / 5 // 6 % 7 ** 2
bitwise = 0xFF & 0x0F | 0xF0 ^ 0xAA << 2 >> 1
logical = True and False or not False
compare = 1 < 2 <= 3 == 3 != 4 >= 4 > 0
ident = x is None, x is not None, x in [x], x not in []
walrus = (n := 10)
lst = [value * value for value in range(10) if value % 2 == 0]
dct = {k: v for k, v in items.items()}
st = {value % 7 for value in range(20)}
gen = (value for value in range(5))
nest = [cell for row in matrix for cell in row]
# ── Functions and classes ─────────────────────────────────────────────────
def simple(a, b=1, *args, kw=0, kw2=None, **kwargs):
return a + b + kw + len(args) + len(kwargs)
def posonly(a, b, /, c, d):
return a + b + c + d
def with_annotations(x: int, y: str = "hi") -> bool:
return bool(x) and bool(y)
def generator():
yield 1
yield from range(2, 4)
def decorator(fn):
return fn
def deco_factory(arg, **kwargs):
def apply(fn):
return fn
return apply
@decorator
@deco_factory("arg")
@deco_factory("named", key="value")
def decorated() -> str:
return "decorated"
class Base:
"""Class docstring."""
class_var: int = 0
__slots__ = ("x",)
def __init__(self) -> None:
self.x = 0
def __repr__(self) -> str:
return f"{type(self).__name__}()"
@classmethod
def create(cls) -> "Base":
return cls()
@staticmethod
def util(value: int) -> int:
return value * 2
@property
def value(self) -> int:
return self.x
@value.setter
def value(self, v: int) -> None:
self.x = v
class Child(Base, metaclass=type):
pass
class Stack(Generic[T]):
def __init__(self, values: Optional[list[T]] = None) -> None:
self.values = values or []
def push(self, value: T) -> None:
self.values.append(value)
def first(self) -> T:
return self.values[0]
@overload
def first_item(value: list[int]) -> int: ...
@overload
def first_item(value: list[str]) -> str: ...
def first_item(value):
return value[0]
x_opt: Optional[int] = None
y_union: Union[int, str] = 0
z_pipe: int | str | None = 0
w_final: Final[int] = 42
l_lit: Literal["a", "b", 1] = "a"
# ── Async, context, match, regex ──────────────────────────────────────────
class AsyncContext:
async def __aenter__(self) -> "AsyncContext":
return self
async def __aexit__(self, exc_type, exc, tb) -> None:
return None
async def coro() -> None:
await asyncio.sleep(0)
async def agen():
for value in range(3):
yield value
async def use_async() -> list[int]:
async with AsyncContext() as ctx:
await coro()
return [value async for value in agen() if value > 0]
def showcase_runtime() -> tuple[bool, str]:
match command:
case {"action": "quit"}:
mode = "quit"
case {"action": str(action), "val": int(value)} if value > 0:
mode = action
case [first, *rest]:
mode = f"list:{first}:{len(rest)}"
case _:
mode = "other"
pat = re.compile(r"""
^(?P<word>[a-z_]+) # word
(?P<digits>\d+)? # optional digits
$
""".strip(), re.VERBOSE)
return pat.match("token42") is not None, mode
def main() -> None:
stack = Stack[int]([1, 2, 3])
ok, mode = showcase_runtime()
total = sum(generator()) + dec + len(keyword.kwlist) + stack.first()
print("hello from verbose py", total, ok, mode, first_item(["x", "y"]))
if __name__ == "__main__":
main()
PY
hello from verbose py 84 True quit x
Took 0.2s