Python TutorialGetting Started with PythonPython Basic SyntaxPython DatatypesPython IndentationPython Collection TypesPython Basic Input and OutputPython Built in Modules and FunctionsPython FunctionsChemPy - python packageCreating Python packagesFunctional Programming in PythonIncompatibilities moving from Python 2 to Python 3IoT Programming with Python and Raspberry PIKivy - Cross-platform Python Framework for NUI DevelopmentMutable vs Immutable (and Hashable) in PythonPyInstaller - Distributing Python CodePython *args and **kwargsPython 2to3 toolPython Abstract Base Classes (abc)Python Abstract syntax treePython Alternatives to switch statement from other languagesPython and ExcelPython Anti-PatternsPython ArcPyPython ArraysPython Asyncio ModulePython Attribute AccessPython AudioPython Binary DataPython Bitwise OperatorsPython Boolean OperatorsPython Checking Path Existence and PermissionsPython ClassesPython CLI subcommands with precise help outputPython Code blocks, execution frames, and namespacesPython Collections modulePython Comments and DocumentationPython Common PitfallsPython Commonwealth ExceptionsPython ComparisonsPython Complex mathPython concurrencyPython ConditionalsPython configparserPython Context Managers (with Statement)Python Copying dataPython CountingPython ctypesPython Data SerializationPython Data TypesPython Database AccessPython Date and TimePython Date FormattingPython DebuggingPython DecoratorsPython Defining functions with list argumentsPython DeploymentPython Deque ModulePython DescriptorPython Design PatternsPython DictionaryPython Difference between Module and PackagePython DistributionPython DjangoPython Dynamic code execution with `exec` and `eval`Python EnumPython ExceptionsPython ExponentiationPython Files & Folders I/OPython FilterPython FlaskPython Functools ModulePython Garbage CollectionPython GeneratorsPython getting start with GZipPython graph-toolPython groupby()Python hashlibPython HeapqPython Hidden FeaturesPython HTML ParsingPython HTTP ServerPython IdiomsPython ijsonPython Immutable datatypes(int, float, str, tuple and frozensets)Python Importing modulesPython Indexing and SlicingPython Input, Subset and Output External Data Files using PandasPython Introduction to RabbitMQ using AMQPStorm

Python 2to3 tool

From WikiOD

Syntax[edit | edit source]

  • $ 2to3 [-options] path/to/

Parameters[edit | edit source]

Parameter Description
filename / directory_name 2to3 accepts a list of files or directories which is to be transformed as its argument. The directories are recursively traversed for Python sources.
Option Option Description
-f FIX, --fix=FIX Specify transformations to be applied; default: all. List available transformations with --list-fixes
-j PROCESSES, --processes=PROCESSES Run 2to3 concurrently
-x NOFIX, --nofix=NOFIX Exclude a transformation
-l, --list-fixes List available transformations
-p, --print-function Change the grammar so that print() is considered a function
-v, --verbose More verbose output
--no-diffs Do not output diffs of the refactoring
-w Write back modified files
-n, --nobackups Do not create backups of modified files
-o OUTPUT_DIR, --output-dir=OUTPUT_DIR Place output files in this directory instead of overwriting input files. Requires the -n flag, as backup files are unnecessary when the input files are not modified.
-W, --write-unchanged-files Write output files even is no changes were required. Useful with -o so that a complete source tree is translated and copied. Implies -w.
--add-suffix=ADD_SUFFIX Specify a string to be appended to all output filenames. Requires -n if non-empty. Ex.: --add-suffix='3' will generate .py3 files.

Remarks[edit | edit source]

The 2to3 tool is an python program which is used to convert the code written in Python 2.x to Python 3.x code. The tool reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code.

The 2to3 tool is available in the standard library as lib2to3 which contains a rich set of fixers that will handle almost all code. Since lib2to3 is a generic library, it is possible to write your own fixers for 2to3.

Basic Usage[edit | edit source]

Consider the following Python2.x code. Save the file as

Python 2.x2.0

def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()

In the above file, there are several incompatible lines. The raw_input() method has been replaced with input() in Python 3.x and print is no longer a statement, but a function. This code can be converted to Python 3.x code using the 2to3 tool.

Unix[edit | edit source]

$ 2to3

Windows[edit | edit source]

> path/to/

Running the above code will output the differences against the original source file as shown below.

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored
***    (original)
+++    (refactored)
@@ -1,5 +1,5 @@
 def greet(name):
*    print "Hello, {0}!".format(name)
*print "What's your name?"
*name = raw_input()
+    print("Hello, {0}!".format(name))
+print("What's your name?")
+name = input()
RefactoringTool: Files that need to be modified:

The modifications can be written back to the source file using the -w flag. A backup of the original file called is created, unless the -n flag is given.

Unix[edit | edit source]

$ 2to3 -w

Windows[edit | edit source]

> path/to/ -w

Now the file has been converted from Python 2.x to Python 3.x code.

Once finished, will contain the following valid Python3.x code:

Python 3.x3.0

def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()