blob: 4d64af8c94a74a8025f6f6f4990a76d1967c9a24 [file] [log] [blame]
Benjamin Petersond6313712008-07-31 16:23:04 +00001.. _2to3-reference:
2
32to3 - Automated Python 2 to 3 code translation
4===============================================
5
6.. sectionauthor:: Benjamin Peterson
7
82to3 is a Python program that reads your Python 2.x source code and applies a
9series of *fixers* to transform it into valid Python 3.x code.
10
11
12Using 2to3
13----------
14
152to3 can be run with a list of files to transform or a directory to recursively
16traverse looking for files with the ``.py`` extension.
17
18Here is a sample Python 2.x source file, :file:`example.py`::
19
20 def greet(name):
21 print "Hello, {0}!".format(name)
22 print "What's your name?"
23 name = raw_input()
24 greet(name)
25
26It can be converted to Python 3.x code via 2to3 on the command line::
27
28 $ 2to3 example.py
29
30A diff against the original source file will be printed. 2to3 can also write
31the needed modifications right back to the source file. (A backup of the
32original file will also be made.) This is done with the :option:`-w` flag::
33
34 $ 2to3 -w example.py
35
36:file:`example.py` will now look like this::
37
38 def greet(name):
39 print("Hello, {0}!".format(name))
40 print("What's your name?")
41 name = input()
42 greet(name)
43
44Comments and and exact indentation will be preserved throughout the translation
45process.
46
47By default, 2to3 will run a set of predefined fixers. The :option:`-l` flag
48lists all avaible fixers. An explicit set of fixers to run can be given by use
49of the :option:`-f` flag. The following example runs only the ``imports`` and
50``has_key`` fixers::
51
52 $ 2to3 -f imports -f has_key example.py
53
54Some fixers are *explicit*, meaning they aren't run be default and must be
55listed on the command line. Here, in addition to the default fixers, the
56``idioms`` fixer is run::
57
58 $ 2to3 -f all -f idioms example.py
59
60Notice how ``all`` enables all default fixers.
61
62Sometimes 2to3 will find will find a place in your source code that needs to be
63changed, but 2to3 cannot fix automatically. In this case, 2to3 will print a
64warning beneath the diff for a file.
65
66
67:mod:`lib2to3` - 2to3's library
68-------------------------------
69
70.. module:: lib2to3
71 :synopsis: the 2to3 library
72.. moduleauthor:: Guido van Rossum
73.. moduleauthor:: Collin Winter
74
75.. XXX What is the public interface anyway?