blob: 6255a2ee437b5a016d17f266b2a8b39c5d76772a [file] [log] [blame]
Benjamin Peterson40202212008-07-24 02:45:37 +00001.. _2to3-reference:
2
32to3 - Automated Python 2 to 3 code translation
4===============================================
5
Benjamin Peterson51a37032009-01-11 19:48:15 +00006.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson40202212008-07-24 02:45:37 +00007
Benjamin Petersoneb55fd82008-09-03 00:21:32 +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
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000010contains a rich set of fixers that will handle almost all code. 2to3 supporting
11library :mod:`lib2to3` is, however, a flexible and generic library, so it is
12possible to write your own fixers for 2to3. :mod:`lib2to3` could also be
13adapted to custom applications in which Python code needs to be edited
14automatically.
Benjamin Peterson40202212008-07-24 02:45:37 +000015
16
Benjamin Petersone0820e22009-02-07 23:01:19 +000017.. _2to3-using:
18
Benjamin Peterson40202212008-07-24 02:45:37 +000019Using 2to3
20----------
21
Benjamin Peterson15ad6c02008-09-04 23:31:27 +0000222to3 will usually be installed with the Python interpreter as a script. It is
23also located in the :file:`Tools/scripts` directory of the Python root.
24
252to3's basic arguments are a list of files or directories to transform. The
26directories are to recursively traversed for Python sources.
Benjamin Peterson40202212008-07-24 02:45:37 +000027
28Here is a sample Python 2.x source file, :file:`example.py`::
29
30 def greet(name):
Georg Brandl340739e2008-07-24 07:09:21 +000031 print "Hello, {0}!".format(name)
Benjamin Peterson40202212008-07-24 02:45:37 +000032 print "What's your name?"
33 name = raw_input()
34 greet(name)
35
36It can be converted to Python 3.x code via 2to3 on the command line::
37
38 $ 2to3 example.py
39
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000040A diff against the original source file is printed. 2to3 can also write the
41needed modifications right back to the source file. (Of course, a backup of the
Benjamin Petersonf3d0ce12008-10-19 19:39:16 +000042original is also be made unless :option:`-n` is also given.) Writing the
43changes back is enabled with the :option:`-w` flag::
Benjamin Peterson40202212008-07-24 02:45:37 +000044
45 $ 2to3 -w example.py
46
Benjamin Petersonad2a9e72008-09-06 03:00:00 +000047After transformation, :file:`example.py` looks like this::
Benjamin Peterson40202212008-07-24 02:45:37 +000048
49 def greet(name):
Benjamin Peterson3ac2f242008-07-25 21:59:53 +000050 print("Hello, {0}!".format(name))
Benjamin Peterson40202212008-07-24 02:45:37 +000051 print("What's your name?")
52 name = input()
53 greet(name)
54
Benjamin Petersoncd29e9d2008-10-22 21:05:30 +000055Comments and exact indentation are preserved throughout the translation process.
Benjamin Peterson40202212008-07-24 02:45:37 +000056
Benjamin Petersone0820e22009-02-07 23:01:19 +000057By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`. The
58:option:`-l` flag lists all available fixers. An explicit set of fixers to run
59can be given with :option:`-f`. Likewise the :option:`-x` explicitly disables a
60fixer. The following example runs only the ``imports`` and ``has_key`` fixers::
Benjamin Peterson40202212008-07-24 02:45:37 +000061
62 $ 2to3 -f imports -f has_key example.py
63
Benjamin Peterson0ecbcca2008-10-13 21:51:40 +000064This command runs every fixer except the ``apply`` fixer::
65
66 $ 2to3 -x apply example.py
67
Benjamin Peterson92be5392008-10-22 20:57:43 +000068Some fixers are *explicit*, meaning they aren't run by default and must be
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000069listed on the command line to be run. Here, in addition to the default fixers,
70the ``idioms`` fixer is run::
Benjamin Peterson40202212008-07-24 02:45:37 +000071
72 $ 2to3 -f all -f idioms example.py
73
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000074Notice how passing ``all`` enables all default fixers.
Benjamin Peterson40202212008-07-24 02:45:37 +000075
Benjamin Peterson92be5392008-10-22 20:57:43 +000076Sometimes 2to3 will find a place in your source code that needs to be changed,
77but 2to3 cannot fix automatically. In this case, 2to3 will print a warning
78beneath the diff for a file. You should address the warning in order to have
79compliant 3.x code.
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000080
812to3 can also refactor doctests. To enable this mode, use the :option:`-d`
Benjamin Petersonb51f81d2008-09-28 01:53:29 +000082flag. Note that *only* doctests will be refactored. This also doesn't require
83the module to be valid Python. For example, doctest like examples in a reST
84document could also be refactored with this option.
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000085
Benjamin Peterson0ecbcca2008-10-13 21:51:40 +000086The :option:`-v` option enables output of more information on the translation
87process.
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000088
Benjamin Petersone0820e22009-02-07 23:01:19 +000089When the :option:`-p` is passed, the :2to3fixer:`print` fixer ``print`` as a
90function instead of a statement. This is useful when ``from __future__ import
91print_function`` is being used. If this option is not given, the print fixer
92will surround print calls in an extra set of parentheses because it cannot
93differentiate between the print statement with parentheses (such as ``print
94("a" + "b" + "c")``) and a true function call.
95
96
97.. _2to3-fixers:
98
99Fixers
100------
101
102Each step of tranforming code is encapsulated in a fixer. The command ``2to3
103-l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on
104and off individually. They are described here in more detail.
105
106
107.. 2to3fixer:: apply
108
109 Removes usage of :func:`apply`. For example ``apply(function, *args,
110 **kwargs)`` is converted to ``function(*args, **kwargs)``.
111
112.. 2to3fixer:: basestring
113
114 Converts :class:`basestring` to :class:`str`.
115
116.. 2to3fixer:: buffer
117
118 Converts :class:`buffer` to :class:`memoryview`. This fixer is optional
119 because the :class:`memoryview` API is similar but not exactly the same as
120 that of :class:`buffer`.
121
122.. 2to3fixer:: callable
123
124 Converts ``callable(x)`` to ``hasattr(x, "__call_")``.
125
126.. 2to3fixer:: dict
127
128 Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to
129 :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and
130 :meth:`dict.itervalues` to :meth:`dict.values`. It also wraps existing
131 usages of :meth:`dict.items`, :meth:`dict.keys`, and :meth:`dict.values` in a
132 call to :class:`list`.
133
134.. 2to3fixer:: except
135
136 Converts ``except X, T`` to ``except X as T``.
137
138.. 2to3fixer:: exec
139
140 Converts the :keyword:`exec` statement to the :func:`exec` function.
141
142.. 2to3fixer:: execfile
143
144 Removes usage of :func:`execfile`. The argument to :func:`execfile` is
145 wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`.
146
147.. 2to3fixer:: filter
148
149 Wraps :func:`filter` in a :class:`list` call.
150
151.. 2to3fixer:: funcattrs
152
153 Fixes function attributes that have been renamed. For example,
154 ``my_function.func_closure`` is converted to ``my_function.__closure__``.
155
156.. 2to3fixer:: future
157
158 Removes ``from __future__ import new_feature`` statements.
159
160.. 2to3fixer:: getcwdu
161
162 Renames :func:`os.getcwdu` to :func:`os.getcwd`.
163
164.. 2to3fixer:: has_key
165
166 Changes ``dict.has_key(key)`` to ``key in dict``.
167
168.. 2to3fixer:: idioms
169
170 This optional fixer preforms several transformations that make Python code
171 more idiomatic. Type comparisions like ``type(x) is SomeClass`` and
172 ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``.
173 ``while 1`` becomes ``while True``. This fixer also tries to make use of
174 :func:`sorted` in appropiate places. For example, this block ::
175
176 L = list(some_iterable)
177 L.sort()
178
179 is changed to ::
180
181 L = sorted(some_iterable)
182
183.. 2to3fixer:: import
184
185 Detects sibling imports and converts them to relative imports.
186
187.. 2to3fixer:: imports
188
189 Handles module renames in the standard library.
190
191.. 2to3fixer:: imports2
192
193 Handles other modules reanmes in the standard library. It is separate from
194 :2to3fixer:`imports` only because of technical limitations.
195
196.. 2to3fixer:: input
197
198 Converts ``input(prompt)`` to ``eval(input(prompt))``
199
200.. 2to3fixer:: intern
201
202 Converts :func:`intern` to :func:`sys.itern`.
203
204.. 2to3fixer:: isinstance
205
206 Fixes duplicate types in the second argument of :func:`isinstance`. For
207 example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x,
208 (int))``.
209
210.. 2to3fixer:: itertools_imports
211
212 Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and
213 :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also
214 changed to :func:`itertools.filterfalse`.
215
216.. 2to3fixer:: itertools
217
218 Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
219 :func:`itertools.imap` to their builtin equivalents.
220 :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.
221
222.. 2to3fixer:: long
223
224 Strips the ``L`` prefix on numbers and renamed :class:`long` to :class:`int`.
225
226.. 2to3fixer:: map
227
228 Wraps :func:`map` in a :class:`list` call. It also changes ``map(none, x)``
229 to ``list(x)``. Using ``from future_builtins import map`` disables this
230 fixer.
231
232.. 2to3fixer:: metaclass
233
234 Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class
235 body) to the new (``class X(metaclass=Meta)``).
236
237.. 2to3fixer:: methodattrs
238
239 Fixes old method attribute names. For example, ``meth.im_func`` is converted
240 to ``meth.__func__``.
241
242.. 2to3fixer:: ne
243
244 Converts the old not-equal syntax, ``<>``, to ``!=``.
245
246.. 2to3fixer:: next
247
248 Converts the use of iterator's :meth:`next` methods to the :func:`next`
249 function. It also renames :meth:`next` methods to :meth:`~object.__next__`.
250
251.. 2to3fixer:: nonzero
252
253 Renames :meth:`~object.__nonzero__` to :meth:`~object.__bool__`.
254
255.. 2to3fixer:: paren
256
257 Add extra parenthesis where they are required in list comprehensions. For
258 example, ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``.
259
260.. 2to3fixer:: print
261
262 Converts the :keyword:`print` statement to the :func:`print` function.
263
264.. 2to3fixer:: raises
265
266 Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` as ``raise
267 E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be
268 incorrect because substituting tuples for exceptions has been removed in 3.0.
269
270.. 2to3fixer:: raw_input
271
272 Converts :func:`raw_input` to :func:`input`.
273
274.. 2to3fixer:: reduce
275
276 Handles the move of :func:`reduce` to :func:`functools.reduce`.
277
278.. 2to3fixer:: renames
279
280 Changes :data:`sys.maxint` to :data:`sys.maxsize`.
281
282.. 2to3fixer:: repr
283
284 Replaces backtick repr with the :func:`repr` function.
285
286.. 2to3fixer:: set_literal
287
288 Replaces use of the :class:`set` constructor with set literals. This fixer
289 is optional.
290
291.. 2to3fixer:: standard_error
292
293 Renames :exc:`StandardError` to :exc:`Exception`.
294
295.. 2to3fixer:: sys_exc
296
297 Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`,
298 :data:`sys.exc_traceback` to use :func:`sys.exc_info`.
299
300.. 2to3fixer:: throw
301
302 Fixes the API change in generators :meth:`throw` method.
303
304.. 2to3fixer:: tuple_params
305
306 Removes implicit tuple parameter unpacking. This fixer inserts temporary
307 variables.
308
309.. 2to3fixer:: types
310
311 Fixes code broken from the removal of some members in the :mod:`types`
312 module.
313
314.. 2to3fixer:: unicode
315
316 Renames :class:`unicode` to :class:`str`.
317
318.. 2to3fixer:: urllib
319
320 Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib`
321 package.
322
323.. 2to3fixer:: ws_comma
324
325 Removes excess whitespace from comma separated items. This fixer is
326 optional.
327
328.. 2to3fixer:: xrange
329
330 Renames :func:`xrange` to :func:`range` and wraps existing :func:`range`
331 calls with :class:`list`.
332
333.. 2to3fixer:: xreadlines
334
335 Change ``for x in file.xreadlines()`` to ``for x in file``.
336
337.. 2to3fixer:: zip
338
339 Wraps :func:`zip` usage in a :class:`list` call. This is disabled when
340 ``from future_builtins import zip`` appears.
Benjamin Peterson40202212008-07-24 02:45:37 +0000341
342
Benjamin Peterson40202212008-07-24 02:45:37 +0000343:mod:`lib2to3` - 2to3's library
344-------------------------------
345
346.. module:: lib2to3
347 :synopsis: the 2to3 library
348.. moduleauthor:: Guido van Rossum
349.. moduleauthor:: Collin Winter
350
Benjamin Peterson7f8f6602008-09-27 16:23:55 +0000351
352.. warning::
353
354 The :mod:`lib2to3` API should be considered unstable and may change
355 drastically in the future.
356
Benjamin Peterson40202212008-07-24 02:45:37 +0000357.. XXX What is the public interface anyway?