Playbook

How to modernize Python 2 codebase

How to modernize Python 2 codebase in safe steps: pin what you have, add tests, convert module by module, and avoid a big-bang rewrite.

By the Cloudverg engineering team · · 6 min read

The problem

Python 2 reached end of life on January 1, 2020. It gets no security fixes, and a growing number of libraries have dropped it. Your pip installs start failing, your base images age out, and the one engineer who knew the build is gone. Meanwhile the code still earns money, so nobody wants to touch it.

The usual advice is to rewrite it. That's rarely right. A rewrite freezes feature work for months, throws away years of bug fixes that live in odd-looking lines, and ships all its risk on one day. Most Python 2 code is closer to Python 3 than people think. The language changes are mechanical. The hard parts are hidden: strings and bytes, integer division, and dependencies that only exist for Python 2.

So the real problem is not syntax. It's that you can't see what the code does, you can't prove a change is safe, and you have no way back if something breaks. Fix those three things first and the conversion gets boring, which is what you want.

What a good solution looks like

A good modernization keeps the system running the whole time. Every step is small enough to ship on its own, and every step has a rollback. At no point do you have a branch that is three months old and impossible to merge.

The end state is one codebase that runs on a supported Python 3 release, with pinned dependencies, a test suite that fails when behavior changes, and a build that runs in CI. Along the way you'll go through a middle state: code that runs on both Python 2 and Python 3. That's the safety net. It lets you move one module, one service or one cron job at a time and keep production on the old interpreter until you're ready.

The order matters more than the tooling. Inventory, then tests, then dependencies, then syntax, then the string and bytes work, then the cutover. Skip ahead and you'll be debugging three problems at once.

How to build it

Start with an inventory. List every entry point: web apps, workers, cron scripts, one-off admin tools. Run pip freeze in each environment and write down every package and version. Note which ones have no Python 3 release. Those are your real blockers, and you want to find them in week one, not week ten. For each, decide: upgrade, swap for a maintained alternative, vendor a small copy, or delete the feature.

Next, get tests around the code you plan to change. You don't need full coverage. Write characterization tests that record what the code does today, ugly outputs included. Feed real input files and real API payloads through the main paths and save the results. Where there are no tests and no time, run the old and new versions side by side on production-like data and diff the output.

Then go to the dual-version stage. Upgrade to the last Python 2.7 release and fix the warnings you get when you run with the -3 flag. Add the six library or the future package so one file can run under both. Use python-modernize or futurize to do the mechanical rewrites: print statements, dict.iteritems, xrange, except syntax, relative imports. Review the diffs by hand. Add from __future__ import division, print_function and absolute_import at the top of each file so behavior matches Python 3 before you switch.

The string work deserves its own pass. In Python 2, str is bytes and unicode is text, and the code mixes them freely. Decide where bytes become text: decode at the edges (files, sockets, database drivers, HTTP) and work in text inside. Open files with an explicit encoding. Check pickles, since old pickles can fail to load under Python 3 without help. Check anything that hashes or signs a string. Integer division is the other quiet one: 7 / 2 changes meaning, so grep for division on values that feed money or counts.

Finally, cut over one deployable at a time. Run the Python 3 build in CI next to the Python 2 build, then in staging, then for a slice of production traffic or one background job. Keep the Python 2 image around and tagged until the new one has run through a full business cycle, including month end.

Risks and how to manage them

The biggest risk is silent data change. A bytes and text mix-up usually doesn't crash. It writes a wrong character to the database or changes a checksum. Guard the boundaries with tests that use non-ASCII names, odd encodings from old files, and binary blobs. Compare database rows written by both versions before you trust the new one.

The second risk is dependencies that can't move. A package with no Python 3 version can stall the project for weeks. Find these early and make a call per package. Sometimes the answer is a small internal replacement, and sometimes it's removing a feature nobody uses. Ask the people who use the system before you spend a week porting something dead.

The third is scope creep. Modernizing tempts people to also reformat everything, adopt a new framework and add type hints in the same pull request. Don't. Keep conversion commits mechanical and separate from behavior changes, so a bad deploy points to one small diff. Add type hints and cleanups after cutover.

Last, keep a rollback at every stage: the old image, the old requirements file, a feature flag or a traffic split you can flip back in minutes. If a step has no rollback, make the step smaller until it does.

How to measure success

Measure progress by things you can count without arguing. How many entry points run on Python 3 in production. How many dependencies still lack a Python 3 release. How many modules pass under both interpreters in CI. Watch those numbers move each week, and the project stops feeling like a fog.

Measure safety by what doesn't happen. No rise in error rates after a cutover, no diffs between old and new output on your comparison runs, no data repair scripts. If you had to roll back, note how long it took. A rollback that takes minutes means the plan is working, even if you used it.

Measure the payoff afterward. Can a new hire set up the project from the README in a morning? Do security scanners stop flagging the interpreter? Can you upgrade a library without a week of dread? Once Python 2 is gone from your images and CI, delete the compatibility shims and run a final cleanup so you don't carry six forever.

If the system is old, the author has left and you're not sure where to begin, Cloudverg offers a Legacy modernization sprint at $8,500/month (fixed scope, 3 weeks, renews monthly until cancelled). It covers the inventory, a ranked risk list and a step-by-step migration sequence with rollback points. It's one option alongside doing the inventory in-house.

Frequently asked questions

Can I migrate Python 2 to Python 3 without stopping feature work?

Yes. Move to a dual-version codebase first, then convert and deploy one module or service at a time. Feature work continues on the same branch because every step is small and mergeable.

What breaks most often when moving from Python 2 to Python 3?

String and bytes handling, integer division, and dependencies with no Python 3 release. Syntax changes are mostly automatic. Encoding bugs are the ones that slip through, so test with non-ASCII data and binary files.

Should I rewrite instead of converting?

Usually no. A rewrite delivers all its risk at once and discards fixes buried in the old code. Convert in steps unless the design itself is the problem, and decide that after you have an inventory, not before.

Monthly plan

Want help with this? Legacy modernization sprint

$8,500/month

3 weeks · Starts within 10 business days

Three weeks to understand an old system nobody wants to touch, rank the risks and agree a step by step plan that avoids a big bang rewrite.

Renews monthly. Cancel any time.
Prefer to pay once?

Pay $8,500 once for one month of the Legacy modernization sprint. It ends on its own, nothing renews.

What is included

Related guides

More custom software guides   Custom software

Smallest way to start

Get a senior architect on your problem this week

Ninety minutes a month on the cloud, AI or security question that is blocking you, a pre-read of your material and a written summary within two business days.

$450/month

Renews monthly. Cancel any time.
Prefer to pay once?

Pay $450 once for one month of the Expert architecture session. It ends on its own, nothing renews.