[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"VVTr775xZ3":3},"# lean-py\n\nEffortless interop between **Lean 4** and **Python**, in both directions.\n\n* **Lean -> Python.** Annotate any Lean definition with `@[python \"name\"]`\n  and call it from Python with automatic type marshalling.\n  `derive_python` exposes inductives and structures as Python constructors.\n* **Python -> Lean.** `LeanPy.Python` gives Lean code a `Py` type with\n  `import_`, `eval`, `exec`, `getAttr`, `call`, etc. CPython is loaded\n  lazily via `dlopen`.\n* **Kernel facade.** `LeanPy.Kernel` wraps the\n  [Pantograph](https://github.com/leanprover/Pantograph) library so a\n  Python process can drive Lean's type-checker, elaborator, and tactic\n  engine without spawning a subprocess.\n\n## Install\n\n### Python side\n\n```bash\nuv pip install \"lean_py @ git+https://github.com/BasisResearch/lean.py\"\n```\n\nor in `pyproject.toml`:\n\n```toml\n[project]\ndependencies = [\"lean_py @ git+https://github.com/BasisResearch/lean.py\"]\n```\n\nThe Python package discovers `lean.h` and `libleanshared` from the active\nLean toolchain at import time. You need a working\n[elan](https://github.com/leanprover/elan) install (`lean` on PATH).\n\n### Lean side\n\nAdd to your `lakefile.toml`:\n\n```toml\n[[require]]\nname = \"LeanPy\"\ngit  = \"https://github.com/BasisResearch/lean.py\"\n\n[[lean_lib]]\nname = \"MyLib\"\n# These three lines are required:\nmoreLinkObjs = [\n  \"LeanPy/LeanPy:static\",\n  \"LeanPy/leanPyNative:static\",\n  \"Pantograph/Pantograph:static\",\n]\nprecompileModules = true\ndefaultFacets = [\"shared\"]\n# macOS only — allows install_name_tool to rewrite @rpath references:\nmoreLinkArgs = [\"-Wl,-headerpad_max_install_names\"]\n```\n\n> **Why three static libs?** `LeanPy:static` is the Lean module,\n> `leanPyNative:static` is the C bridge (`python_bridge.c`), and\n> `Pantograph:static` is the proof-assistant kernel that `LeanPy.Kernel`\n> depends on. All three must be linked into the shared library that\n> Python loads.\n\nThen build:\n\n```bash\nlake build           # fetches LeanPy + Pantograph, compiles everything\n```\n\n## Using additional Lake dependencies\n\nIf your project depends on other Lean libraries (Batteries, Mathlib,\nyour own packages, etc.), add them as normal `[[require]]` entries in\nyour `lakefile.toml`. Any library whose symbols are called at runtime\nthrough the Python-loaded `.so`/`.dylib` must also appear in\n`moreLinkObjs`:\n\n```toml\n[[require]]\nname = \"LeanPy\"\ngit  = \"https://github.com/BasisResearch/lean.py\"\n\n[[require]]\nname = \"batteries\"\ngit  = \"https://github.com/leanprover-community/batteries\"\nrev  = \"main\"\n\n[[lean_lib]]\nname = \"MyLib\"\nmoreLinkObjs = [\n  \"LeanPy/LeanPy:static\",\n  \"LeanPy/leanPyNative:static\",\n  \"Pantograph/Pantograph:static\",\n  # Add any additional deps whose symbols you call at runtime:\n  \"batteries/Batteries:static\",\n]\nprecompileModules = true\ndefaultFacets = [\"shared\"]\nmoreLinkArgs = [\"-Wl,-headerpad_max_install_names\"]\n```\n\n**Rule of thumb:** if `lake build` succeeds but Python fails with\n`symbol not found`, add the missing package to `moreLinkObjs` as\n`\"\u003Cpackage>/\u003CLibName>:static\"`. The pattern is always\n`\"\u003Clake-package-name>/\u003Clean_lib-name>:static\"`.\n\nIf you only `import` a library at compile time (e.g. for notation or\nmacros) but don't call its functions at runtime, you don't need it in\n`moreLinkObjs`.\n\n## Quick start\n\n### 1. Write Lean code\n\n```lean\n-- MyLib.lean\nimport LeanPy\nopen LeanPy\n\n@[python \"add\"]\ndef add (a b : Int) : Int := a + b\n\nstructure Point where\n  x : Int\n  y : Int\n\nderive_python Point\n\n@[python \"origin\"]\ndef origin (_ : Unit) : Point := { x := 0, y := 0 }\n\n#export_python_registry \"MyLib\"   -- makes the registry visible to Python\n```\n\n### 2. Call from Python\n\n```python\nfrom lean_py import LeanLibrary\n\nlib = LeanLibrary.from_lake(\"path/to/lake/project\", \"MyLib\", build=True)\n\nlib.add(3, 4)          # 7\nlib.origin(None)       # Point.mk(0, 0)\nlib.Point(10, 20)      # Point.mk(10, 20) — constructed in Python\n```\n\n`from_lake` finds the `.lake/build/lib/lib\u003CName>.{dylib,so}` produced by\n`lake build`. Pass `build=True` to run `lake build` automatically.\n\n## Calling Python from Lean\n\n```lean\nopen LeanPy.Python in\n@[python \"numpy_dot\"]\ndef numpyDot (xs ys : Array Int) : IO Int := do\n  init ()                         -- dlopens libpython once\n  let np ← import_ \"numpy\"\n  let dot ← np.getAttr \"dot\"\n  let a ← Py.ofList (xs.toList.map Py.ofInt)\n  let b ← Py.ofList (ys.toList.map Py.ofInt)\n  (← dot.call #[← a, ← b]).toInt\n```\n\n```python\nlib.numpy_dot([1, 2, 3], [4, 5, 6])   # 32\n```\n\n## Kernel facade (Pantograph)\n\nDrive Lean's type-checker and tactic engine from Python:\n\n```python\nfrom lean_py import LeanLibrary\nfrom lean_py.kernel import Kernel\n\nlib = LeanLibrary.from_lake(\"path/to/project\", \"MyLib\", build=True)\nk = Kernel(lib)\nk.load([\"Init\"])\n\n# Create a goal and run tactics\nstate = k.goal_create(\"∀ n : Nat, n + 0 = n\")\nprint(state.pretty())             # ⊢ ∀ (n : Nat), n + 0 = n\n\nresult = state.try_tactic(\"intro n\")\nprint(result.state.pretty())      # n : Nat\\n⊢ n + 0 = n\n\nresult2 = result.state.try_tactic(\"simp\")\nprint(result2.state.is_solved())  # True\n```\n\nThe kernel API also exposes environment introspection (`catalog`,\n`decl_type`, `module_of`, ...), expression elaboration (`infer_type`,\n`pretty_print`, `whnf`), frontend processing, and goal-state pickling.\nSee `lean_py/kernel.py` for the full surface.\n\n## z3py-compatible prover\n\nLean's `grind` tactic is a powerful automated reasoning engine — congruence\nclosure, arithmetic, and more — but calling it means setting up a Lake\nproject, marshalling goal strings, and threading tactic results. `lean_py.z3`\nwraps all of that behind a z3py-compatible API so you can write propositions\nin Python and prove them with one call.\n\n```python\nfrom lean_py.z3 import *\n\nx, y = Ints('x y')\nprove(Implies(And(x > 0, y > 0), x + y > 0))   # prints \"proved\"\n```\n\nExpressions build up Lean syntax under the hood. Operator overloading on\n`ArithRef` (`+`, `-`, `*`, `\u003C`, `\u003C=`, ...) and `BoolRef` (`&`, `|`, `~`)\nworks exactly like z3py. Free variables are tracked automatically and bound\nas `∀` quantifiers at proof time.\n\n```python\n# Solver interface — same as z3py\ns = Solver()\ns.add(x > 0, x \u003C 0)\ns.check()              # unsat (negation proved via grind)\n\n# Quantifiers, uninterpreted sorts, functions\nEntity = DeclareSort('Entity')\nMan = Function('Man', Entity, BoolSort())\nMortal = Function('Mortal', Entity, BoolSort())\nsocrates = Const('socrates', Entity)\ne = Const('e', Entity)\n\nprove(Implies(\n    And(ForAll([e], Implies(Man(e), Mortal(e))),\n        Man(socrates)),\n    Mortal(socrates),\n))                     # proved\n```\n\nThe solver tries tactics in order: `grind`, `omega`, `decide`, `simp_all`.\nBecause Lean is a proof checker and not an SMT solver, `check()` returns\n`unsat` (negation proved) or `unknown` — never `sat`. Model extraction is\nnot supported.\n\n### Setup\n\nThe z3 layer needs a `Kernel` to talk to Lean. Two options:\n\n**Manual** — point at an existing Lake project (the kernel facade you\nalready know):\n\n```python\nfrom lean_py import LeanLibrary\nfrom lean_py.kernel import Kernel\nfrom lean_py.z3 import *\n\nlib = LeanLibrary.from_lake(\"path/to/project\", \"MyLib\", build=True)\nk = Kernel(lib)\nk.init_search(\"\")\nk.load([\"Init\"])\nset_kernel(k)\n\nprove(Int('x') + 0 == Int('x'))\n```\n\n**Zero-config** — `ManagedProject` creates and caches a Lake project\nunder `~/.lean_py/managed/` so you never touch a lakefile:\n\n```python\nfrom lean_py.project import ManagedProject\nfrom lean_py.z3 import *\n\nmp = ManagedProject.get(deps=(\"batteries\",))  # fetches + builds once\nset_kernel(mp.kernel())\n\nx = Int('x')\nprove(Implies(x > 0, x + 1 > 0))\n```\n\n`ManagedProject` pins dependencies to your active Lean toolchain version\n(e.g. `batteries@v4.29.1` for `leanprover/lean4:v4.29.1`). Supported\nwell-known packages: `batteries`, `mathlib`, `aesop`, `proofwidgets`.\nPass any other name and it will be added as a bare `[[require]]` entry —\nyou'll need to specify the git source yourself. For example, to use a\ncustom package `MyMathUtils`:\n\n```python\nmp = ManagedProject.get(deps=(\"batteries\", \"MyMathUtils\"))\n```\n\nThis generates a `lakefile.toml` with:\n\n```toml\n[[require]]\nname = \"batteries\"\ngit  = \"https://github.com/leanprover-community/batteries\"\nrev  = \"v4.29.1\"\n\n[[require]]\nname = \"MyMathUtils\"\n```\n\nYou'd then edit `~/.lean_py/managed/\u003Chash>/lakefile.toml` to add the\ngit source for `MyMathUtils` before the first build:\n\n```toml\n[[require]]\nname = \"MyMathUtils\"\ngit  = \"https://github.com/yourorg/my-math-utils\"\nrev  = \"main\"\n```\n\n## Bidirectional introspection\n\nLean's kernel ADTs (`Lean.Expr`, `Lean.Name`, `Lean.Level`,\n`Lean.Syntax`, ...) are exposed as Python values via `derive_python`\n(registered in `LeanPy/Reflect.lean`):\n\n```python\nName = lib.Name\nExpr = lib.Expr\n\n# Build a Lean.Expr tree in Python\nnat  = Name.str(Name.anonymous, \"Nat\")\nsucc = Expr.const(Name.str(nat, \"succ\"), [])\nzero = Expr.const(Name.str(nat, \"zero\"), [])\ne    = Expr.app(succ, zero)       # Nat.succ Nat.zero\n\n# Pass it to any @[python] function expecting Lean.Expr\nlib.describe_expr(e)\n```\n\nGoing the other way, `Py` values returned from Lean land as live Python\nobjects:\n\n```python\nlib.makeList123(None)   # [1, 2, 3]  (not an opaque handle)\n```\n\n## Type stubs\n\nA `LeanLibrary` exposes its functions and types dynamically, so editors and\ntype-checkers see only `Any`. Generate a `.pyi` stub from the same registry\nthat drives marshalling — one source of truth for runtime conversion *and*\nstatic types:\n\n```bash\npython -m lean_py.stubgen path/to/project MyLib -o MyLib.pyi\n```\n\nor at runtime:\n\n```python\nlib = LeanLibrary.from_lake(\"path/to/project\", \"MyLib\", build=True)\nlib.write_stub(\"MyLib.pyi\")\n```\n\nThe stub declares a `MyLibLibrary(LeanLibrary)` subclass with typed methods\n(`def add(self, a0: int, a1: int, /) -> int: ...`) and one class per derived\ntype, including per-constructor classes for pattern matching. Annotate the\n`from_lake` result to opt in:\n\n```python\nfrom MyLib import MyLibLibrary  # the generated stub\nlib: MyLibLibrary = LeanLibrary.from_lake(\"path/to/project\", \"MyLib\")  # type: ignore[assignment]\nlib.add(3, 4)          # checked: (int, int) -> int\n```\n\nParameter *names* are not in the registry yet, so parameters are positional\n(`a0, a1, ...`), matching the runtime wrappers, which reject keyword arguments.\n\nThe stub annotations come from the same `TypeRepr` that drives marshalling, so\nthey can't drift from runtime behaviour. That representation also backs an\noptional runtime check — one description, static hints and value validation\nalike:\n\n```python\nfrom lean_py import set_argument_typechecking\n\nset_argument_typechecking(True)\nlib.add(3, \"four\")     # TypeError: add arg 1: expected `Int` (int), got str 'four'\n```\n\nIt is off by default (the marshaller is deliberately lenient); enable it while\ndeveloping for clearer errors before values cross the FFI boundary.\n\n## Distribution: self-contained wheels\n\nBy default a `LeanLibrary` discovers the Lean runtime from the active toolchain\n(`lean --print-prefix`), so every user needs elan installed. To ship a library\nthat installs with **no toolchain**, bundle the dylib together with its Lean\nruntime dependency closure into a wheel:\n\n```bash\npython -m lean_py.packaging build path/to/project MyLib --version 0.1.0 -o dist/\n```\n\nThe bundler vendors the dylib, the Lean runtime shared libraries, and `lean.h`\ninto the wheel, and rewrites their install names / RPATHs so they resolve each\nother via `@loader_path` (macOS) or `$ORIGIN` (Linux). The wheel ships a loader:\n\n```python\nfrom mylib import load          # the bundled package\nlib = load()                    # a ready LeanLibrary, no elan required\nlib.myFunction(42)\n```\n\nBecause lean.py binds through **ctypes** rather than a CPython C-extension, the\nwheel is ABI-independent and tagged `py3-none-\u003Cplatform>` — the only\nplatform-specific content is the vendored dylibs. (This is the analogue of\nnerodia's `abi3` wheels; lean.py needs no Python-ABI tag at all.) Bundling\nrequires `install_name_tool`/`codesign` on macOS or `patchelf` on Linux.\n\n## Exceptions\n\nErrors carry type information across the boundary:\n\n```python\nfrom lean_py import LeanError, LeanPyCallbackError\n\ntry:\n    lib.some_io_function()\nexcept LeanPyCallbackError as e:    # Python error inside a Lean callback\n    print(e.python_type, e.python_message)\nexcept LeanError as e:              # Lean IO error\n    print(e.kind, e.message)\n```\n\n## Examples\n\n```\nexamples/\n  01_basic/             tiny end-to-end demo\n  02_pantograph_kernel/ Pantograph-style kernel facade\n  03_numpy_typed/       numpy with Lean-checked dependent shapes\n  04_sympy_tactic/      `by sympy` — Lean tactic backed by SymPy via Expr trees\n  05_knuckledragger/    `by knuckle` — Lean tactic backed by Z3 via Expr trees\n  06_effectful_verifier/ side-effectful programs with verified pre/post specs\n  07_z3py_drop_in/      z3py vocabulary backed by Lean's grind (no Z3 needed)\n```\n\nEach is a self-contained Lake + uv project.\n\n## Tests\n\n```bash\nuv sync --dev\nlake build\ncd tests/lean && lake build TestLib:shared && cd ../..\nuv run pytest tests -v\n```\n\n1300+ tests across 17 files covering: FFI primitives, all marshalled\ntypes, typed exceptions, bidirectional introspection, kernel facade (goal\nstate, tactics, environment, elaboration, frontend, serialisation),\nPython-in-Lean demos, the z3py-compatible layer, and refcount stress tests.\n\n## How it works\n\n1. `@[python \"name\"]` sets `@[export]` and registers metadata (parameter\n   types, return type) in a persistent env extension.\n2. `derive_python TypeName` walks an inductive's constructors and adds\n   them to the same registry.\n3. `#export_python_registry \"Prefix\"` serialises the registry to JSON and\n   emits two `@[export]`'d C functions returning that JSON.\n4. On the Python side, `LeanLibrary` dlopens the `.dylib`/`.so`, calls\n   `Prefix_funcs_json()` / `Prefix_types_json()`, builds `TypeWrapper`s,\n   and exposes one Python callable per registered function.\n5. The C bridge (`LeanPy/native/python_bridge.c`) implements the\n   Python-in-Lean direction: a `lean_external_class` over `PyObject*`\n   plus `lean_py_*` externs.\n\n## Repository layout\n\n```\nLeanPy.lean              root import\nLeanPy/\n  Attr.lean              @[python] attribute, derive_python\n  Export.lean            #export_python_registry\n  Python.lean            Py type + @[extern] bridge\n  Reflect.lean           derive_python for Lean.Expr/Name/Level/...\n  Kernel.lean            Pantograph kernel API\n  Kernel/                Frontend, Compat, ...\n  native/python_bridge.c C bridge (dlopen, no Python.h)\n\nlean_py/\n  __init__.py            public API\n  library.py             LeanLibrary loader\n  marshal.py             Lean \u003C-> Python marshalling\n  kernel.py              Kernel / GoalState / TacticResult\n  registry.py            TypeRepr / FuncInfo mirrors\n  _runtime.py            dynamic ctypes FFI from lean.h\n  _parse.py              lean.h parser (pycparser)\n  utils.py               toolchain helpers\n  project.py             ManagedProject (zero-config Lake projects)\n  z3/                    z3py-compatible prover (core AST + solver)\n\nexamples/                self-contained demos\ntests/                   125-test suite\n```\n\n## License\n\nApache 2.0. See [LICENSE](LICENSE).\n",1795981065450]