Agent skill

Python To Lean4 Translator

by ArabelaTso in ArabelaTso/Skills-4-SE

Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety.

Apache-2.0Auto-check passedDevelopment

Install Python To Lean4 Translator

skills CLI
$ npx skills add ArabelaTso/Skills-4-SE --skill python-to-lean4-translator -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ArabelaTso/Skills-4-SE python-to-lean4-translator --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/python-to-lean4-translator .claude/skills/python-to-lean4-translator && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
python-to-lean4-translator
GitHub stars
253
Token cost
~2.2k tokens
SKILL.md length
651 words
Files
4 (incl. references)
Skills in repo
150
Repo updated
First seen
Licence
Apache-2.0

At a glance

Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety.

  • Works in 12 steps: Type Safety First → Preserve Semantics → Ensure Executability → …
  • Users ask to convert
  • SKILL.md covers Overview, Translation Workflow, Core Translation Principles and Type Mapping Reference, plus 7 more sections
  • Calls python

What it does

Python To Lean4 Translator is an agent skill from ArabelaTso/Skills-4-SE. Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety. Use when users ask to convert, translate, or port Python code to Lean4, or when they need to verify Python algorithms using Lean4's theorem proving capabilities. Handles functions, classes, data structures, control flow, and ensures the generated Lean4 code is well-typed, executable, and can successfully run.

Its SKILL.md is about 2.2k tokens, which your agent loads only when the skill is triggered. The skill folder holds 4 other files, including reference files (for example `references/advanced_features.md`, `references/common_patterns.md` and `references/type_mappings.md`).

It sits in Development, covering Translation and Type safety. It works with Python. The repository describes itself as: A curated list of 180+ useful Claude Skills for Software Engineering and resources for customizing AI for SE workflows. The licence is Apache-2.0.

When your agent uses it

  • Users ask to convert
  • Port Python code to Lean4
  • They need to verify Python algorithms using Lean4s theorem proving capabilities

Example prompts

  • “/python-to-lean4-translator”

Requirements

  • Python 3

Workflow steps

12 steps, taken from the step headings in SKILL.md.

  1. Type Safety First
  2. Preserve Semantics
  3. Ensure Executability
  4. Dynamic Typing
  5. Mutability
  6. Exceptions
  7. Recursion and Termination
  8. Side Effects and I/O
  9. Analyze Python Code
  10. Plan Type Mappings
  11. Translate Constructs
  12. Ensure Well-Typedness

What it can do on your machine

Read from SKILL.md and the folder at commit 4f38503. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • python

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Python To Lean4 Translator loads about 2.2k tokens when it runs, and up to ~7.1k if it reads all its reference files. Until then it costs about 110 tokens; SKILL.md has 651 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~110
When it runs · the whole SKILL.md, loaded when a task matches
~2.2k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~7.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ArabelaTso/Skills-4-SE at commit 4f38503, republished under its Apache-2.0 licence (© ArabelaTso). 651 words, ~2,174 tokens.

Download SKILL.mdSave it as .claude/skills/python-to-lean4-translator/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
python-to-lean4-translator
description
Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety. Use when users ask to convert, translate, or port Python code to Lean4, or when they need to verify Python algorithms using Lean4's theorem proving capabilities. Handles functions, classes, data structures, control flow, and ensures the generated Lean4 code is well-typed, executable, and can successfully run.

Python to Lean4 Translator

Translate Python programs into equivalent, executable Lean4 code while preserving program semantics and ensuring type safety.

Overview

This skill provides systematic guidance for translating Python code to Lean4, handling type inference, function translations, data structures, control flow, and ensuring well-typed, executable output.

Translation Workflow

Python Input → Analyze Structure → Map Types → Translate Constructs → Verify → Output Lean4
    ├─ Identify types and signatures
    ├─ Map Python constructs to Lean4 equivalents
    ├─ Handle type conversions
    ├─ Ensure totality and termination
    └─ Validate executability

Core Translation Principles

1. Type Safety First

Lean4 is strongly typed. Every translation must:

  • Infer or specify explicit types for all variables
  • Ensure type consistency across operations
  • Handle Python's dynamic typing by choosing appropriate Lean4 types
  • Use Option for nullable values, Except for error handling
2. Preserve Semantics

The translated code must maintain the same computational behavior, preserve function input-output relationships, keep the same algorithmic complexity, and handle edge cases equivalently.

3. Ensure Executability

Generated Lean4 code must compile without errors, be executable (use #eval to verify), terminate (prove termination for recursive functions), and follow Lean4 syntax and conventions.

Type Mapping Reference

Basic Types
Python TypeLean4 TypeNotes
intInt or NatUse Nat for non-negative integers
floatFloatLean4's floating point type
boolBoolDirect mapping
strStringDirect mapping
NoneOption αUse none for None, some x for values
listList αHomogeneous lists
tupleProduct types α × β or custom structure
dictStd.HashMap or List (α × β)Requires import
setStd.HashSet or List αRequires import

For detailed type system information, see references/type_mappings.md.

Translation Patterns

Functions

Simple function:

python
def add(a: int, b: int) -> int:
    return a + b

Lean4:

lean
def add (a : Int) (b : Int) : Int :=
  a + b

Recursive function:

python
def factorial(n: int) -> int:
    if n <= 1:
        return 1
    else:
        return n * factorial(n - 1)

Lean4:

lean
def factorial (n : Nat) : Nat :=
  if n ≤ 1 then
    1
  else
    n * factorial (n - 1)
Control Flow

If-else:

python
if condition:
    result = value1
else:
    result = value2

Lean4:

lean
let result := if condition then value1 else value2

For loops (list iteration):

python
total = 0
for x in items:
    total += x

Lean4 (using fold):

lean
let total := items.foldl (· + ·) 0
List Operations

List comprehension:

python
squares = [x * x for x in range(10)]

Lean4:

lean
let squares := (List.range 10).map (fun x => x * x)

Filter:

python
evens = [x for x in numbers if x % 2 == 0]

Lean4:

lean
let evens := numbers.filter (fun x => x % 2 == 0)
Classes and Structures

Python class:

python
class Rectangle:
    def __init__(self, width: int, height: int):
        self.width = width
        self.height = height

    def area(self) -> int:
        return self.width * self.height

Lean4:

lean
structure Rectangle where
  width : Int
  height : Int

def Rectangle.area (r : Rectangle) : Int :=
  r.width * r.height

Handling Common Challenges

1. Dynamic Typing

Analyze usage to infer types, use sum types for multiple possible types, use Option for nullable values, and document type assumptions.

2. Mutability

Use immutable bindings with let, thread state through function parameters, or use monadic state (StateM) if needed.

3. Exceptions

Convert Python exceptions to Except or Option:

python
def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Division by zero")
    return a / b

Lean4:

lean
def divide (a b : Int) : Except String Float :=
  if b = 0 then
    Except.error "Division by zero"
  else
    Except.ok (a.toFloat / b.toFloat)
4. Recursion and Termination

Use structural recursion when possible, add termination_by clause for complex recursion:

lean
def fibonacci (n : Nat) : Nat :=
  match n with
  | 0 => 0
  | 1 => 1
  | n + 2 => fibonacci n + fibonacci (n + 1)
termination_by n
5. Side Effects and I/O

Use IO monad for I/O operations:

python
def greet(name: str):
    print(f"Hello, {name}!")

Lean4:

lean
def greet (name : String) : IO Unit :=
  IO.println s!"Hello, {name}!"

Translation Process

Step 1: Analyze Python Code

Identify all functions, classes, and global variables. Infer types from usage and annotations. Identify dependencies and imports. Note any dynamic behavior or side effects.

Step 2: Plan Type Mappings

Map Python types to Lean4 types. Identify where Option, Except, or sum types are needed. Plan structure definitions for classes. Determine function signatures.

Show full SKILL.md (250 more words)Show less
Step 3: Translate Constructs

Start with data structures (classes → structures). Translate pure functions first. Handle control flow (convert loops to recursion). Translate functions with side effects using IO. Add necessary imports.

Step 4: Ensure Well-Typedness

Add explicit type annotations. Resolve type mismatches. Handle implicit conversions. Add termination proofs for recursive functions.

Step 5: Verify Executability

Check syntax with Lean4 compiler. Test with #eval for simple cases. Verify output matches Python behavior. Document any semantic differences.

Required Imports

Common imports for translated code:

lean
import Std.Data.HashMap
import Std.Data.HashSet
import Init.Data.List.Basic
import Init.Data.Option.Basic

Example Translation

Python:

python
def is_prime(n: int) -> bool:
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

def primes_up_to(limit: int) -> list[int]:
    return [n for n in range(2, limit + 1) if is_prime(n)]

Lean4:

lean
def isPrime (n : Nat) : Bool :=
  if n < 2 then
    false
  else
    let rec checkDivisors (i : Nat) : Bool :=
      if i * i > n then
        true
      else if n % i = 0 then
        false
      else
        checkDivisors (i + 1)
    checkDivisors 2

def primesUpTo (limit : Nat) : List Nat :=
  (List.range (limit + 1)).drop 2 |>.filter isPrime

-- Test
#eval primesUpTo 20  -- [2, 3, 5, 7, 11, 13, 17, 19]

Best Practices

  1. Start Simple: Translate simple functions first, then build up to complex ones
  2. Test Incrementally: Use #eval to test each function as you translate
  3. Document Assumptions: Note any assumptions about types or behavior
  4. Preserve Structure: Keep similar code organization when possible
  5. Use Lean4 Idioms: Prefer pattern matching over if-else chains
  6. Handle Errors Explicitly: Use Option or Except instead of exceptions
  7. Prove Termination: Add termination proofs for recursive functions
  8. Comment Differences: Note where Lean4 behavior differs from Python

Verification Checklist

Before finalizing translation:

  • All types are explicitly specified or correctly inferred
  • Code compiles without errors
  • #eval produces expected results for test cases
  • Recursive functions have termination proofs
  • Error handling uses Option or Except appropriately
  • Side effects are properly wrapped in IO
  • Imports are included
  • Comments explain non-obvious translations

Additional Resources

For complex translations, refer to:

© ArabelaTso, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files (references) in skills/python-to-lean4-translator of ArabelaTso/Skills-4-SE.

  • SKILL.md
  • references/advanced_features.md
  • references/common_patterns.md
  • references/type_mappings.md

Open the folder on GitHubat commit 4f38503

Compare with similar skills

Python To Lean4 Translator next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Python To Lean4 Translator compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Python To Lean4 Translator this skillArabelaTso/Skills-4-SE253—~2.2kAutomated safety check: PassApache-2.0
Ok Script TasksAliceJump/ok-gf2274—~1kAutomated safety check: PassNone
Python Scala Oopbenchflow-ai/skillsbench1.8k—~1.9kAutomated safety check: PassApache-2.0
Minimizing Ty Ecosystem Changesastral-sh/ruff50k—~4.6kAutomated safety check: PassMIT
Kedro Babysitkedro-org/kedro11k—~4kAutomated safety check: PassCustom licence
Dignified Python Standardsdocling-project/docling69k—~1.5kAutomated safety check: PassApache-2.0

Similar skills

  • Ok Script Tasks

    AliceJump/ok-gf2

    Create and modify automation task classes for the ok-script Python library in ok-gf2, including BaseTask one-time tasks, TriggerTask background tasks, task config UI metadata, registration in…

    274 GitHub stars~1k tokensUpdated today
    DevelopmentAuto-check passed
  • Python Scala Oop

    benchflow-ai/skillsbench

    Guide for translating Python classes, inheritance, and object-oriented patterns to Scala.

    1.8k GitHub stars~1.9k tokensUpdated 2 mo ago
    DevelopmentAuto-check passed
  • Official

    A skill your agent uses when a user says "minimize this ty ecosystem change", "reproduce this ecosystem result", "investigate a primer difference", "investigate a mypyprimer difference"…

    50k GitHub stars~4.6k tokensUpdated today
    DevelopmentAuto-check passed
  • Kedro Babysit

    kedro-org/kedro

    Run Kedro's local lint / format / type-check / tests on changed files (uses the project's pre-commit hooks, ruff, mypy, pytest, lint-imports, detect-secrets, Make targets — in the right venv), or…

    11k GitHub stars~4k tokensUpdated today
    DevelopmentAuto-check passed
  • Dignified Python Standards

    docling-project/docling

    Applies opinionated production Python conventions chosen by the project's Python version: modern type syntax, pathlib, explicit checks and interface guidance.

    69k GitHub stars~1.5k tokensUpdated today
    DevelopmentAuto-check passed
  • Rust Ffi

    ariebovenberg/whenever

    Instructions for using whenever's internal Rust FFI abstractions

    2.4k GitHub stars~2.5k tokensUpdated yesterday
    DevelopmentAuto-check passed

More from ArabelaTso/Skills-4-SE

All 150 skills in this repo
  • Framework Migration Assistant

    ArabelaTso/Skills-4-SE

    Automatically migrate Python web applications between frameworks (Flask → FastAPI, Django → FastAPI).

    253 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Metamorphic Test Generator

    ArabelaTso/Skills-4-SE

    Generate test cases using metamorphic testing by applying transformations based on metamorphic properties.

    253 GitHub stars~798 tokensUpdated 1 mo ago
    Auto-check passed
  • Reproduction Trace Instrumenter

    ArabelaTso/Skills-4-SE

    Instruments programs to capture execution traces specifically for reproducing reported bugs, enabling consistent replay and diagnosis of failures.

    253 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Spring Mvc To Boot Migrator

    ArabelaTso/Skills-4-SE

    Automatically migrate Spring MVC applications to Spring Boot.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed
  • State Snapshot Instrumenter

    ArabelaTso/Skills-4-SE

    Instrument programs (Python, C/C++, Java) to capture snapshots of key program states at runtime, including variables, memory, and call stacks.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Python To Lean4 Translator

What does Python To Lean4 Translator do?

Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety. Python To Lean4 Translator is an agent skill from ArabelaTso/Skills-4-SE. Translate Python programs to equivalent Lean4 code while preserving semantics and ensuring type safety.

When should I use Python To Lean4 Translator?

Python To Lean4 Translator fits situations like: users ask to convert; port Python code to Lean4; they need to verify Python algorithms using Lean4s theorem proving capabilities.

How do I install Python To Lean4 Translator in Claude Code?

Run `npx skills add ArabelaTso/Skills-4-SE --skill python-to-lean4-translator -a claude-code`. Or copy the skill folder (skills/python-to-lean4-translator in ArabelaTso/Skills-4-SE) into .claude/skills/python-to-lean4-translator in your project. Claude Code loads it when a task matches its description.

How do I install Python To Lean4 Translator in Codex?

Run `npx skills add ArabelaTso/Skills-4-SE --skill python-to-lean4-translator -a codex`. Or copy the skill folder (skills/python-to-lean4-translator in ArabelaTso/Skills-4-SE) into .agents/skills/python-to-lean4-translator in your project. Codex loads it when a task matches its description.

Can I use Python To Lean4 Translator in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ArabelaTso/Skills-4-SE --skill python-to-lean4-translator -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/python-to-lean4-translator, .gemini/skills/python-to-lean4-translator, .github/skills/python-to-lean4-translator and .opencode/skills/python-to-lean4-translator in your project.

What does Python To Lean4 Translator need to run?

Going by SKILL.md and its folder, Python To Lean4 Translator needs the command-line tools its instructions call (python). Our summary lists: Python 3.

Does Python To Lean4 Translator access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Python To Lean4 Translator safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Python To Lean4 Translator use?

Python To Lean4 Translator is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Python To Lean4 Translator use?

About 2.2k tokens (SKILL.md is roughly 8.7k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4.9k tokens, read only when the agent opens those files.

What are the alternatives to Python To Lean4 Translator?

Skills that share tags, products or a category with Python To Lean4 Translator: Ok Script Tasks (AliceJump/ok-gf2, 274 stars), Python Scala Oop (benchflow-ai/skillsbench, 1.8k stars), Minimizing Ty Ecosystem Changes (astral-sh/ruff, 50k stars) and Kedro Babysit (kedro-org/kedro, 11k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Python To Lean4 Translator?

ArabelaTso (a GitHub user) maintains it in ArabelaTso/Skills-4-SE, which has 253 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on August 21, 2026.

Source: ArabelaTso/Skills-4-SE on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.