Skip to main content
Migrating from Python 2 to Python 3 involves several syntax and API changes. This guide will walk you through using Codegen to automate this migration, handling print statements, string handling, iterators, and more.
You can find the complete example code in our examples repository.

Overview

The migration process involves five main steps:
  1. Converting print statements to function calls
  2. Updating Unicode to str
  3. Converting raw_input to input
  4. Updating exception handling syntax
  5. Modernizing iterator methods
Let’s walk through each step using Codegen.

Step 1: Convert Print Statements

First, we need to convert Python 2’s print statements to Python 3’s print function calls:
This transforms code from:
to:
In Python 3, print is a function rather than a statement, requiring parentheses around its arguments.

Step 2: Update Unicode to str

Next, we update Unicode-related code to use Python 3’s unified string type:
This converts code from:
to:
Python 3 unifies string types, making the unicode type and u prefix unnecessary.

Step 3: Convert raw_input to input

Python 3 renames raw_input() to input():
This updates code from:
to:
Python 3’s input() function always returns a string, like Python 2’s raw_input().

Step 4: Update Exception Handling

Python 3 changes the syntax for exception handling:
This converts code from:
to:
Python 3 uses as instead of a comma to name the exception variable.

Step 5: Update Iterator Methods

Finally, we update iterator methods to use Python 3’s naming:
This transforms iterator classes from:
to:
Python 3 renames the next() method to __next__() for consistency with other special methods.

Running the Migration

You can run the complete migration using our example script:
The script will:
  1. Process all Python files in your codebase
  2. Apply the transformations in the correct order
  3. Maintain your code’s functionality while updating to Python 3 syntax

Next Steps

After migration, you might want to:
  • Add type hints to your code
  • Use f-strings for string formatting
  • Update dependencies to Python 3 versions
  • Run the test suite to verify functionality
Check out these related tutorials:

Learn More