Benjamin Peterson | d631371 | 2008-07-31 16:23:04 +0000 | [diff] [blame] | 1 | .. _2to3-reference: |
| 2 | |
| 3 | 2to3 - Automated Python 2 to 3 code translation |
| 4 | =============================================== |
| 5 | |
| 6 | .. sectionauthor:: Benjamin Peterson |
| 7 | |
| 8 | 2to3 is a Python program that reads your Python 2.x source code and applies a |
| 9 | series of *fixers* to transform it into valid Python 3.x code. |
| 10 | |
| 11 | |
| 12 | Using 2to3 |
| 13 | ---------- |
| 14 | |
| 15 | 2to3 can be run with a list of files to transform or a directory to recursively |
| 16 | traverse looking for files with the ``.py`` extension. |
| 17 | |
| 18 | Here 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 | |
| 26 | It can be converted to Python 3.x code via 2to3 on the command line:: |
| 27 | |
| 28 | $ 2to3 example.py |
| 29 | |
| 30 | A diff against the original source file will be printed. 2to3 can also write |
| 31 | the needed modifications right back to the source file. (A backup of the |
| 32 | original 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 | |
| 44 | Comments and and exact indentation will be preserved throughout the translation |
| 45 | process. |
| 46 | |
| 47 | By default, 2to3 will run a set of predefined fixers. The :option:`-l` flag |
| 48 | lists all avaible fixers. An explicit set of fixers to run can be given by use |
| 49 | of 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 | |
| 54 | Some fixers are *explicit*, meaning they aren't run be default and must be |
| 55 | listed 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 | |
| 60 | Notice how ``all`` enables all default fixers. |
| 61 | |
| 62 | Sometimes 2to3 will find will find a place in your source code that needs to be |
| 63 | changed, but 2to3 cannot fix automatically. In this case, 2to3 will print a |
| 64 | warning 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? |