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