Skip to main content

Claude Prompt to Translate Code Between Languages

Translate code between languages idiomatically: native data structures, error paradigm, type system, tests, and the gotchas that don't translate cleanly.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt

                                

What this prompt does

This prompt structures code translation across seven explicit axes — logic preservation, idiomatic patterns, error handling paradigm, type system, dependencies, performance, and tests — so the model treats each concern independently instead of collapsing them. That separation is what prevents the most common failure mode: writing Python that looks like Java, or TypeScript that looks like C.

The [error_paradigm] and [typing_approach] variables are the ones most people skip, and skipping them is expensive. Specifying Result<T, E> for Rust versus try/catch for Java versus error return values for Go tells the model exactly which idiom to apply, rather than letting it guess and inherit the source language's approach. Naming your [test_framework] — pytest, Jest, Go's testing package — ensures the output is immediately runnable rather than a pseudo-test you have to rewrite anyway.

The "side-by-side comparison" and "gotchas" sections are what make the output trustworthy for production use. Silent behavior differences — integer division rounding, null handling, default argument mutability — get surfaced explicitly rather than buried in code you have to diff manually.

When to use it

  • Porting a Python data-pipeline script to Go for latency-sensitive production use
  • Translating legacy PHP business logic to TypeScript for a Node.js rewrite
  • Converting a Rust CLI tool to Python so a non-systems team can maintain it
  • Moving Java Spring service logic to Kotlin during a codebase modernisation
  • Adapting a JavaScript utility library to Swift for a native iOS client
  • Translating C algorithm implementations to Rust while preserving memory safety guarantees

Example output

For a Python requests-based HTTP retry function translated to Go, the model produces all four requested sections:

## Idiomatic Go translation

- Replaced `requests.Session` with `net/http.Client` + `http.Transport`
- `urllib3.Retry` logic re-implemented with a `for` loop and `time.Sleep` — no stdlib equivalent
- Error handling: returns `([]byte, error)`; caller checks `err != nil`
- Equivalent library: `github.com/hashicorp/go-retryablehttp` if you prefer not to hand-roll

## Side-by-side comparison

| Python                      | Go                                         |
|-----------------------------|--------------------------------------------|
| `session.get(url)`          | `client.Do(req)` with `http.NewRequest`    |
| `raise requests.Timeout`    | `return nil, fmt.Errorf("timeout: %w", err)`|
| `response.content`          | `io.ReadAll(resp.Body)` + defer close      |

## Go best practices applied

- Deferred `resp.Body.Close()` on every path to prevent goroutine leaks
- Errors wrapped with `%w` for `errors.Is` compatibility upstream
- Retry count as a named constant, not a magic number

## Gotchas

Python's `requests` follows 3xx redirects automatically. `net/http` does too,
but caps at 10 hops. Set a custom `CheckRedirect` function if your source code
assumes unlimited redirects.

Python raises `requests.Timeout` as an exception; Go returns a non-nil error —
callers that swallow errors will silently succeed where Python would panic.

## Functionality that doesn't translate directly

`urllib3.Retry` supports per-status-code backoff strategies with no Go stdlib
equivalent. Workaround: use `go-retryablehttp`, or implement a backoff slice
(`[]time.Duration{1s, 2s, 4s}`) and index into it on each retry.

## Test (net/http/httptest)

func TestRetryOnServerError(t *testing.T) {
    attempts := 0
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        attempts++
        if attempts < 3 {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        w.Write([]byte("ok"))
    }))
    defer srv.Close()

    body, err := FetchWithRetry(srv.URL, 3)
    if err != nil { t.Fatal(err) }
    if string(body) != "ok" { t.Fatalf("got %s", body) }
    if attempts != 3 { t.Fatalf("expected 3 attempts, got %d", attempts) }
}

Pro tips

  • Fill [error_paradigm] before you run it. Look up the idiom first if needed — "What is the idiomatic error handling pattern in [target_language] for I/O failures?" takes 10 seconds and produces completely different code than leaving it vague. "exceptions" versus Result<T, E> versus sentinel error values are not interchangeable outputs.
  • Chunk large files. This prompt works best on functions under ~150 lines. For a 2,000-line module, extract and translate function by function, then reassemble — the model stays accurate and each diff is individually reviewable.
  • Name your source library explicitly. List it in the prompt body (pandas, lodash, serde) rather than leaving it implicit. The model can then reason about whether a stdlib equivalent exists or whether you need a third-party package, and it will name the specific package rather than describing it generically.
  • Run the translated tests before touching anything else. The [test_framework] output is your regression gate. If the tests pass, the logic translation is correct. If they fail, the bug is in the translation, not your understanding of the original — and you have a reproducible failure to fix from.
  • Treat the "doesn't translate directly" section as your actual porting risk list. Features like Python generators, Rust lifetimes, or Go goroutines have no 1:1 equivalents. Whatever the model flags there deserves a full code review. The rest usually does not.

Frequently Asked Questions

Will this prompt work for translating between dynamically and statically typed languages, like Python to TypeScript?
Yes, and the `[typing_approach]` variable is specifically for this. Set it to something like "strict TypeScript with explicit interfaces, no `any`" and the model will infer types from your Python runtime usage rather than defaulting to `any` everywhere. You will still need to review complex cases like a `dict` with mixed value types, but the output gives you a typed starting point rather than a fully untyped skeleton.
Does the prompt handle language-specific concurrency models, like translating Python threading to Go goroutines?
Partially. The gotchas and "doesn't translate directly" sections will flag that a gap exists and describe the semantic difference, but concurrent code is one area the template explicitly calls out as not translating directly. Treat the output as a reference architecture with documented caveats, not a drop-in replacement. Plan a manual review pass on any goroutine, channel, or async pattern the model proposes.
What should I put in `[error_paradigm]` if I don't know the target language well?
Ask a targeted question first: "What is the idiomatic error handling pattern in [target_language] for a function that can fail due to I/O?" Paste the answer directly into `[error_paradigm]`. This two-step approach takes under a minute and produces significantly better output than leaving the field vague — the model will otherwise inherit the source language's error style, which is exactly the failure mode this prompt is designed to prevent.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in AI Coding Assistants

Engr Mejba Ahmed

Engr Mejba Ahmed

Claude Code Expert · Online

👋

Hey there!

Quick Actions

WhatsApp Instant reply

Chat on WhatsApp

+880 1723 741224 · Instant reply

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

[email protected]

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support