2to3 - Automated Python 2 to 3 Code Translation

1.0 · deprecated · verified Thu Apr 16

2to3 is a Python program designed to automatically convert Python 2.x source code into Python 3.x compatible code. It achieves this by applying a series of 'fixers' that address common syntax and API changes between the two major Python versions. The PyPI package `2to3` (version 1.0, last updated September 2018) primarily provides the `2to3` command-line utility, which was historically part of the Python standard library. Its core component, `lib2to3`, has been deprecated since Python 3.11 and is slated for removal in Python 3.13, marking the tool's transition towards obsolescence for active development. As Python 2 reached its End-of-Life in January 2020, the utility's main relevance is for legacy codebase migrations.

Common errors

Warnings

Install

Imports

Quickstart

The `2to3` tool is executed from the command line, pointing it to Python 2.x source files or directories. The `-w` flag writes the changes back to the original files, creating a `.bak` backup. The `--output-dir` option allows writing converted files to a new location, often used with `-n` to prevent backup files and `-W` to write all files, even if unchanged.

# Save your Python 2 code to a file, e.g., 'my_python2_script.py'
# Example content for my_python2_script.py:
# print 'Hello, world!'
# x = raw_input('Enter your name: ')
# print 'Your name is', x

# To see the changes without modifying the file:
# 2to3 my_python2_script.py

# To apply changes directly to the file (creates a .bak backup):
# 2to3 -w my_python2_script.py

# To convert an entire directory to a new output directory:
# mkdir python3_version
# 2to3 --output-dir=python3_version -W -n python2_codebase/

view raw JSON →