Ryz Labs/Migrations/Python 2 to Python 3
Migrations

Python 2 to Python 3 Migration Runbook: Land on a Supported 3.x

A test-first plan for moving Python 2-era code to a supported Python 3 release, covering text and bytes, stored data, C extensions, dependencies and rollback.

A Python 2 to Python 3 migration moves code written for the 2.x semantics of strings, division and iteration onto a currently supported Python 3 release, ideally 3.14, without changing behavior. The safe approach is incremental: pin today's behavior with characterization tests, make the code run on both interpreters, move dependencies and data boundaries, then flip services one at a time with the 2.7 build ready to redeploy. Success is decided by how well you handle the line between bytes and text, because that is where most Python 3 bugs hide and they only surface at runtime.

Why teams migrate now

Python 2 is long past its end. The Python Software Foundation sunset Python 2 on January 1, 2020, and the final release, 2.7.18, shipped in April 2020. Every security fix since then has been for Python 3 only. If you still run 2.7, you are on an interpreter with no upstream patches, usually on old base images, with dependencies frozen at whatever their last 2.7-compatible release was.

The second trap is landing on a Python 3 that is already dead. The Python release status page shows 3.9 reached end of life on 2025-10-31 and 3.10 on 2026-10-01. Many half-finished migrations from earlier years stalled on exactly those versions, so "we're on Python 3" can still mean "we're on an unsupported interpreter". As of today, 3.11 gets security fixes until 2027-10, 3.12 until 2028-10, and 3.13 (now in its security-only phase) until 2029-10. Python 3.14 is in bugfix until 2030-10, and 3.15, first released 2026-10-09, is in bugfix with end of life in 2031-10.

Our recommendation is to target 3.14: it still gets regular bugfix releases, it has had a year for library wheels to catch up, and it buys the longest runway without being brand new. Choose 3.15 if every dependency already publishes wheels for it. Avoid 3.11 and 3.12 as a landing spot; you would be planning the next upgrade before this one is finished.

The business consequences: security reviews and pen tests flag the unsupported interpreter; you cannot adopt current versions of frameworks, SDKs or database drivers; cloud providers and CI vendors retire 2.7 images; and engineers who want to work on modern Python are hard to keep on a 2.7 codebase.

Before you start: inventory and baseline

The strangler-fig plan, phase by phase

For a Python 2 codebase, the strangler pattern works at the level of services and packages. You keep one source tree that runs on both interpreters, then move runtime traffic to Python 3 one deployable at a time, so a bad flip only affects one service and rolls back by redeploying the 2.7 build.

Phase 0: Tests and tooling

Raise coverage where it is thin, starting with the characterization tests above. Add tox or nox with two environments, python2.7 and your 3.x target, and run them in CI from day one. Hosted CI images may no longer ship 2.7, so pin a container image that does. Note that 2to3, the old conversion tool, is gone: Python 3.13 removed 2to3 and lib2to3 after deprecating them in 3.11. Do not build your plan around it. Done when both CI jobs run on every pull request, even if the Python 3 job is still allowed to fail.

Phase 1: Dual-compatible source

Make the code run on both interpreters. Add from __future__ imports (print_function, division, absolute_import, unicode_literals only where you have thought about it) module by module. Use futurize from the python-future project for the mechanical first pass, or six for compatibility shims (six.text_type, six.iteritems, six.moves for renamed standard library modules like urllib2, ConfigParser and cPickle). Fix the syntax that will not parse on Python 3: print statements, except E, e, backtick repr, octal literals such as 0777, exec statements, and raise E, "message". Done when the full suite imports and runs on Python 3, and the Python 3 CI job becomes required.

Phase 2: Semantics, not syntax

This is the real work. Decide a text policy: text is str internally, bytes only at the edges, decoded and encoded explicitly with a named encoding. In 2.7, mixing str and unicode triggers implicit ASCII decoding that works until someone sends a non-ASCII name; in Python 3 the same code raises TypeError or returns b'...' inside a string. Check every open() call: text mode in Python 3 decodes with the locale's encoding unless you pass encoding=, so pass it. Then work through the other semantic changes:

Done when characterization tests pass on both interpreters with identical outputs.

Phase 3: Dependencies, data and C extensions

Upgrade dependencies in steps: first to the last release that still supports 2.7 (to keep CI green on both), then past it once the service flips. For stored data, test that Python 3 can read everything 2.7 wrote. Python 2 pickles containing str load in Python 3 only with pickle.load(f, encoding='latin1') or encoding='bytes', and pickles of datetime or NumPy objects usually need latin1. While both interpreters share a cache or queue, write pickle protocol 2, the highest 2.7 can read. Better, move cross-process data to JSON or another explicit format. For C extensions, the module init and string APIs changed (PyString and PyInt are gone, Py_InitModule becomes PyModule_Create with a PyInit_ function); decide per module whether to port the C, rewrite it in Cython or with cffi, or replace it with pure Python if profiling says you can. Done when every dependency has a version that works on the target, every stored format is proven readable, and every extension builds on the target.

Phase 4: Flip services one at a time

Build each service twice from the same commit, as a 2.7 image and a 3.x image. Shadow traffic first where you can (mirror requests to the Python 3 deployment and compare responses), then canary a small share of real traffic, then all of it. Batch jobs run both versions on the same input and diff the outputs. Done when the Python 3 build carries all traffic with error rate and p95 latency at or better than baseline.

Phase 5: Drop Python 2

Once every deployable runs on Python 3, delete the 2.7 CI job, remove six and the future imports, and run pyupgrade (or Ruff's pyupgrade rules) with your target version to modernize syntax: f-strings, super() without arguments, dict and set comprehensions. Turn on type checking for new code. Done when no 2.7 interpreter in any image, and the lint config pinned to the target version.

PhaseGoalKey techniqueExit criteria
0. Tests and toolingPin current behaviorCharacterization tests, tox/nox matrix with 2.7 and 3.xBoth CI jobs run on every PR
1. Dual-compatible sourceCode imports on both__future__ imports, futurize first pass, six shimsPython 3 CI job required and green
2. SemanticsSame behavior on bothText policy, explicit encodings, // division, explicit sortingIdentical characterization outputs
3. Deps, data, extensionsRemove blockersStaged upgrades, latin1 pickle loading, protocol 2, C API port or Cython/cffiAll deps, data formats and extensions work on target
4. Flip servicesMove runtime trafficDual images per commit, shadow traffic, canary, batch output diffFull traffic on 3.x at or better than baseline
5. Drop Python 2Clean upRemove six and futures, pyupgrade to target, type checksNo 2.7 anywhere

Cutover and rollback

Because the source runs on both interpreters until Phase 5, cutover is a deployment choice, not a code change.

Before any single service flips, confirm all of these:

Undoing each step: Phases 0 to 3 change source only, so rollback is reverting the commit, and the 2.7 job proves it still works. In Phase 4, shift traffic weight back to the 2.7 deployment; workers drain back to the 2.7 consumer group. The one irreversible risk is data written by Python 3 that 2.7 cannot read (pickle protocol 3 or higher, or text written in a new encoding), which is why the protocol and encoding rules apply until every reader has flipped. Phase 5 is only safe once no 2.7 reader remains, so do it last.

Risk matrix

RiskLikelihoodImpactMitigationEarly warning signal
Bytes/text bugs at I/O boundariesHighHighExplicit text policy, encoding= on every open, non-ASCII fixtures in testsTypeError or b'...' strings in logs and rendered pages
Integer division changes resultsMediumHighfrom __future__ import division early, review every / on integersOff-by-one pages, float indexes, TypeError on slicing
Rounding differencesMediumMediumDecimal with explicit rounding in money paths, characterization tests on totalsReport totals off by small amounts
Tests depending on dict or set orderHighLowSort explicitly, run tests with varied PYTHONHASHSEEDFlaky tests that pass on rerun
Stored pickles unreadable or unwritable across versionsMediumHighencoding='latin1' loading, protocol 2 while both run, move to JSONUnicodeDecodeError on cache or queue reads
Abandoned dependency with no Python 3 releaseMediumHighAudit early, pick replacements in Phase 0, vendor and port as a last resortNo release with a Python 3 classifier on PyPI
C extension won't build on targetMediumHighPort to new module init API, or Cython/cffi rewrite, benchmark before and afterImport errors or segfaults in the 3.x CI job
Landing on an EOL 3.xMediumMediumTarget 3.14 (or 3.15 when wheels exist), pin in CI and base imagesBase image or lockfile pinned to 3.9 or 3.10

Typical team shape

Porting 2.7 code is mostly careful Python work plus test discipline, so the team is heavy on senior Python engineers and light on everything else:

Ryz engineers work on your team, reporting to your leads, in your repos and your CI. Many teams begin with a pod of 3 to 5 senior engineers (a tech lead plus engineers), and a full pod is about seven. On price: Ryz engineers on your team start from $7,000 per month (our published range is $7,000–$15,000 per engineer per month, mostly mid-level to senior), quoted per team. Multiply headcount by the number of months and by that rate to get a budget; a well-tested codebase with pure-Python dependencies needs fewer months, and a large monolith with C extensions and pickled state needs more. Once you say go, engineers can typically start in under two weeks. See Python developer rates, or scope your team with us.

Where an AI pod helps (and where it doesn't)

A Python 2 port has a lot of repetitive, well-defined changes, which suits AI-assisted tooling. Our AI pod teams use it to draft characterization tests from recorded inputs and outputs, propose fixes for each failing test in the Python 3 CI job, find every place a str crosses an I/O boundary, write the dependency upgrade pull requests, and cluster shadow-diff failures so engineers look at ten root causes instead of a thousand diffs.

Where it does not help on its own: deciding the text policy, choosing what to do with a C extension, and judging whether a changed output is a bug or a fix. Models are also prone to "fixing" a failing test by changing the expected value. So every generated change goes through human review, the characterization tests are read-only for automated edits, and nothing flips without the shadow diff.

When not to migrate (yet)

Porting is not always the best use of the effort.

Ryz isn't the fit if you want hourly freelance help on a few scripts or a trial before talking to anyone; a freelance marketplace suits that better.

Related

FAQ

How long does a Python 2 to Python 3 migration take?

It depends on the size of the codebase, current test coverage, how many dependencies have no Python 3 release, whether you have C extensions, how much pickled or byte-encoded data is stored, and how many services need to flip. A well-tested service with pure-Python dependencies moves fast; a monolith with low coverage and native code spends most of its time in tests and data boundaries.

Can we run Python 2 and Python 3 side by side?

Yes. Keep one source tree that runs on both, test it on both interpreters in CI, and build two images per commit. Then shift traffic per service with weights or a flag, and keep the 2.7 image deployable until the service has run cleanly on Python 3. Data shared between the two must use formats both can read.

Which Python 3 version should we target?

Target a version with years of support left. Today that means 3.14, which is in its bugfix phase until 2030-10, or 3.15 if all your dependencies already ship wheels for it. Do not land on 3.9 or 3.10, which are already end of life, and treat 3.11 and 3.12 as short stops at best.

Do we need to freeze feature work during the migration?

Usually not. Because the code runs on both interpreters through most of the plan, feature work continues as long as new code passes both CI jobs. Short freezes help only around a high-risk flip, such as a service that writes shared pickled state or depends on a ported C extension.

What does a Python 3 migration cost?

Budget it as engineers times months times the per-engineer monthly rate. Months are driven by test coverage, dependency blockers, native extensions and stored data formats, so the cheapest migrations are the ones that invest in characterization tests first. You get a written plan with named engineers and a per-team price before anything starts.

Questions we didn't answer? Email info@ryzlabs.com.

Thanks — your message has been sent. We’ll get back to you soon.

Something went wrong while sending your message. Please try again or email info@ryzlabs.com.

Explore Ryz Labs

Software development servicesAI development companyIndustriesStaff augmentationAI pod teamsNearshore software developmentHire engineers by roleEngineer ratesGuidesBuyer guidesCase studiesHow we vet engineers

Ryz Labs

Senior engineers on your team. AI pod teams that ship.

Tell us what you're building. You get a scoped plan, a price and the names of the people who would do the work.

  • Only the top 1% of tens of thousands interviewed make it
  • On US business hours, including New York hours
  • Trusted by Fortune 500 engineering teams

Tell us who you need

A Ryz partner replies with a scoped team plan.

Start a conversation →

Prefer to talk? Book a 15-min call →