Migrating from Python 2 to Python 3
Learn how to migrate Python 2 codebases to Python 3 using Codegen
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:
- Converting print statements to function calls
- Updating Unicode to str
- Converting raw_input to input
- Updating exception handling syntax
- 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:
- Process all Python files in your codebase
- Apply the transformations in the correct order
- 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
Was this page helpful?