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