blob: d9eb00c277f684ba886ed59f3e2702038d5e6d87 [file] [log] [blame]
Benjamin Petersond6313712008-07-31 16:23:04 +00001.. _2to3-reference:
2
32to3 - Automated Python 2 to 3 code translation
4===============================================
5
Benjamin Peterson058e31e2009-01-16 03:54:08 +00006.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Petersond6313712008-07-31 16:23:04 +00007
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
Benjamin Petersonae5360b2008-09-08 23:05:23 +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 Petersond6313712008-07-31 16:23:04 +000015
16
Benjamin Petersonf91df042009-02-13 02:50:59 +000017.. _2to3-using:
18
Benjamin Petersond6313712008-07-31 16:23:04 +000019Using 2to3
20----------
21
Benjamin Petersonae5360b2008-09-08 23:05:23 +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 Petersond6313712008-07-31 16:23:04 +000027
28Here is a sample Python 2.x source file, :file:`example.py`::
29
30 def greet(name):
31 print "Hello, {0}!".format(name)
32 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 Petersonae5360b2008-09-08 23:05:23 +000040A diff against the original source file is printed. 2to3 can also write the
Benjamin Petersonad3d5c22009-02-26 03:38:59 +000041needed modifications right back to the source file. (A backup of the original
42file is made unless :option:`-n` is also given.) Writing the changes back is
43enabled with the :option:`-w` flag::
Benjamin Petersond6313712008-07-31 16:23:04 +000044
45 $ 2to3 -w example.py
46
Benjamin Petersonae5360b2008-09-08 23:05:23 +000047After transformation, :file:`example.py` looks like this::
Benjamin Petersond6313712008-07-31 16:23:04 +000048
49 def greet(name):
50 print("Hello, {0}!".format(name))
51 print("What's your name?")
52 name = input()
53 greet(name)
54
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +000055Comments and exact indentation are preserved throughout the translation process.
Benjamin Petersond6313712008-07-31 16:23:04 +000056
Benjamin Petersonf91df042009-02-13 02:50:59 +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 Petersond6313712008-07-31 16:23:04 +000061
62 $ 2to3 -f imports -f has_key example.py
63
Benjamin Peterson206e3072008-10-19 14:07:49 +000064This command runs every fixer except the ``apply`` fixer::
65
66 $ 2to3 -x apply example.py
67
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +000068Some fixers are *explicit*, meaning they aren't run by default and must be
Benjamin Petersonae5360b2008-09-08 23:05:23 +000069listed on the command line to be run. Here, in addition to the default fixers,
70the ``idioms`` fixer is run::
Benjamin Petersond6313712008-07-31 16:23:04 +000071
72 $ 2to3 -f all -f idioms example.py
73
Benjamin Petersonae5360b2008-09-08 23:05:23 +000074Notice how passing ``all`` enables all default fixers.
Benjamin Petersond6313712008-07-31 16:23:04 +000075
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +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 Petersonae5360b2008-09-08 23:05:23 +000080
812to3 can also refactor doctests. To enable this mode, use the :option:`-d`
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +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 Petersonae5360b2008-09-08 23:05:23 +000085
Benjamin Peterson206e3072008-10-19 14:07:49 +000086The :option:`-v` option enables output of more information on the translation
87process.
Benjamin Petersonae5360b2008-09-08 23:05:23 +000088
Benjamin Petersona0dfa822009-11-13 02:25:08 +000089Since some print statements can be parsed as function calls or statements, 2to3
90cannot always read files containing the print function. When 2to3 detects the
91presence of the ``from __future__ import print_function`` compiler directive, it
92modifies its internal grammar to interpert :func:`print` as a function. This
93change can also be enabled manually with the :option:`-p` flag. Use
94:option:`-p` to run fixers on code that already has had its print statements
95converted.
96
Benjamin Petersonf91df042009-02-13 02:50:59 +000097
98.. _2to3-fixers:
99
100Fixers
101------
102
Georg Brandlae2dbe22009-03-13 19:04:40 +0000103Each step of transforming code is encapsulated in a fixer. The command ``2to3
Benjamin Petersonf91df042009-02-13 02:50:59 +0000104-l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on
105and off individually. They are described here in more detail.
106
107
108.. 2to3fixer:: apply
109
110 Removes usage of :func:`apply`. For example ``apply(function, *args,
111 **kwargs)`` is converted to ``function(*args, **kwargs)``.
112
113.. 2to3fixer:: basestring
114
115 Converts :class:`basestring` to :class:`str`.
116
117.. 2to3fixer:: buffer
118
119 Converts :class:`buffer` to :class:`memoryview`. This fixer is optional
120 because the :class:`memoryview` API is similar but not exactly the same as
121 that of :class:`buffer`.
122
123.. 2to3fixer:: callable
124
125 Converts ``callable(x)`` to ``hasattr(x, "__call_")``.
126
127.. 2to3fixer:: dict
128
129 Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to
130 :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and
131 :meth:`dict.itervalues` to :meth:`dict.values`. It also wraps existing
132 usages of :meth:`dict.items`, :meth:`dict.keys`, and :meth:`dict.values` in a
133 call to :class:`list`.
134
135.. 2to3fixer:: except
136
137 Converts ``except X, T`` to ``except X as T``.
138
139.. 2to3fixer:: exec
140
141 Converts the :keyword:`exec` statement to the :func:`exec` function.
142
143.. 2to3fixer:: execfile
144
145 Removes usage of :func:`execfile`. The argument to :func:`execfile` is
146 wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`.
147
148.. 2to3fixer:: filter
149
150 Wraps :func:`filter` usage in a :class:`list` call.
151
152.. 2to3fixer:: funcattrs
153
154 Fixes function attributes that have been renamed. For example,
155 ``my_function.func_closure`` is converted to ``my_function.__closure__``.
156
157.. 2to3fixer:: future
158
159 Removes ``from __future__ import new_feature`` statements.
160
161.. 2to3fixer:: getcwdu
162
163 Renames :func:`os.getcwdu` to :func:`os.getcwd`.
164
165.. 2to3fixer:: has_key
166
167 Changes ``dict.has_key(key)`` to ``key in dict``.
168
169.. 2to3fixer:: idioms
170
Georg Brandlae2dbe22009-03-13 19:04:40 +0000171 This optional fixer performs several transformations that make Python code
172 more idiomatic. Type comparisons like ``type(x) is SomeClass`` and
Benjamin Petersonf91df042009-02-13 02:50:59 +0000173 ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``.
174 ``while 1`` becomes ``while True``. This fixer also tries to make use of
Georg Brandlae2dbe22009-03-13 19:04:40 +0000175 :func:`sorted` in appropriate places. For example, this block ::
Benjamin Petersonf91df042009-02-13 02:50:59 +0000176
177 L = list(some_iterable)
178 L.sort()
179
180 is changed to ::
181
182 L = sorted(some_iterable)
183
184.. 2to3fixer:: import
185
186 Detects sibling imports and converts them to relative imports.
187
188.. 2to3fixer:: imports
189
190 Handles module renames in the standard library.
191
192.. 2to3fixer:: imports2
193
194 Handles other modules renames in the standard library. It is separate from
195 the :2to3fixer:`imports` fixer only because of technical limitations.
196
197.. 2to3fixer:: input
198
199 Converts ``input(prompt)`` to ``eval(input(prompt))``
200
201.. 2to3fixer:: intern
202
203 Converts :func:`intern` to :func:`sys.intern`.
204
205.. 2to3fixer:: isinstance
206
207 Fixes duplicate types in the second argument of :func:`isinstance`. For
208 example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x,
209 (int))``.
210
211.. 2to3fixer:: itertools_imports
212
213 Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and
214 :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also
215 changed to :func:`itertools.filterfalse`.
216
217.. 2to3fixer:: itertools
218
219 Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
Georg Brandl22b34312009-07-26 14:54:51 +0000220 :func:`itertools.imap` to their built-in equivalents.
Benjamin Petersonf91df042009-02-13 02:50:59 +0000221 :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.
222
223.. 2to3fixer:: long
224
225 Strips the ``L`` prefix on long literals and renames :class:`long` to
226 :class:`int`.
227
228.. 2to3fixer:: map
229
230 Wraps :func:`map` in a :class:`list` call. It also changes ``map(None, x)``
231 to ``list(x)``. Using ``from future_builtins import map`` disables this
232 fixer.
233
234.. 2to3fixer:: metaclass
235
236 Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class
237 body) to the new (``class X(metaclass=Meta)``).
238
239.. 2to3fixer:: methodattrs
240
241 Fixes old method attribute names. For example, ``meth.im_func`` is converted
242 to ``meth.__func__``.
243
244.. 2to3fixer:: ne
245
246 Converts the old not-equal syntax, ``<>``, to ``!=``.
247
248.. 2to3fixer:: next
249
Georg Brandl502d9a52009-07-26 15:02:41 +0000250 Converts the use of iterator's :meth:`~iterator.next` methods to the
251 :func:`next` function. It also renames :meth:`next` methods to
252 :meth:`~object.__next__`.
Benjamin Petersonf91df042009-02-13 02:50:59 +0000253
254.. 2to3fixer:: nonzero
255
256 Renames :meth:`~object.__nonzero__` to :meth:`~object.__bool__`.
257
258.. 2to3fixer:: numliterals
259
260 Converts octal literals into the new syntax.
261
262.. 2to3fixer:: paren
263
264 Add extra parenthesis where they are required in list comprehensions. For
265 example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``.
266
267.. 2to3fixer:: print
268
269 Converts the :keyword:`print` statement to the :func:`print` function.
270
271.. 2to3fixer:: raises
272
273 Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise
274 E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be
275 incorrect because substituting tuples for exceptions has been removed in 3.0.
276
277.. 2to3fixer:: raw_input
278
279 Converts :func:`raw_input` to :func:`input`.
280
281.. 2to3fixer:: reduce
282
283 Handles the move of :func:`reduce` to :func:`functools.reduce`.
284
285.. 2to3fixer:: renames
286
287 Changes :data:`sys.maxint` to :data:`sys.maxsize`.
288
289.. 2to3fixer:: repr
290
291 Replaces backtick repr with the :func:`repr` function.
292
293.. 2to3fixer:: set_literal
294
295 Replaces use of the :class:`set` constructor with set literals. This fixer
296 is optional.
297
298.. 2to3fixer:: standard_error
299
300 Renames :exc:`StandardError` to :exc:`Exception`.
301
302.. 2to3fixer:: sys_exc
303
304 Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`,
305 :data:`sys.exc_traceback` to use :func:`sys.exc_info`.
306
307.. 2to3fixer:: throw
308
309 Fixes the API change in generator's :meth:`throw` method.
310
311.. 2to3fixer:: tuple_params
312
313 Removes implicit tuple parameter unpacking. This fixer inserts temporary
314 variables.
315
316.. 2to3fixer:: types
317
318 Fixes code broken from the removal of some members in the :mod:`types`
319 module.
320
321.. 2to3fixer:: unicode
322
323 Renames :class:`unicode` to :class:`str`.
324
325.. 2to3fixer:: urllib
326
327 Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib`
328 package.
329
330.. 2to3fixer:: ws_comma
331
332 Removes excess whitespace from comma separated items. This fixer is
333 optional.
334
335.. 2to3fixer:: xrange
336
337 Renames :func:`xrange` to :func:`range` and wraps existing :func:`range`
338 calls with :class:`list`.
339
340.. 2to3fixer:: xreadlines
341
342 Changes ``for x in file.xreadlines()`` to ``for x in file``.
343
344.. 2to3fixer:: zip
345
346 Wraps :func:`zip` usage in a :class:`list` call. This is disabled when
347 ``from future_builtins import zip`` appears.
Benjamin Petersond6313712008-07-31 16:23:04 +0000348
349
350:mod:`lib2to3` - 2to3's library
351-------------------------------
352
353.. module:: lib2to3
354 :synopsis: the 2to3 library
355.. moduleauthor:: Guido van Rossum
356.. moduleauthor:: Collin Winter
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000357.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Petersond6313712008-07-31 16:23:04 +0000358
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000359
Georg Brandle720c0a2009-04-27 16:20:50 +0000360.. note::
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000361
362 The :mod:`lib2to3` API should be considered unstable and may change
363 drastically in the future.
364
Benjamin Petersond6313712008-07-31 16:23:04 +0000365.. XXX What is the public interface anyway?