blob: bfc1f02335ac707f6200d7b4fd17d1390c1f8dbb [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
Georg Brandl52bc7b82009-02-23 18:33:48 +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 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 Peterson0ac69422009-11-09 04:10:53 +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
Georg Brandl09302282010-10-06 09:32:48 +000092modifies its internal grammar to interpret :func:`print` as a function. This
Benjamin Peterson0ac69422009-11-09 04:10:53 +000093change 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 Petersone0820e22009-02-07 23:01:19 +000097
98.. _2to3-fixers:
99
100Fixers
101------
102
Georg Brandle83a4ad2009-03-13 19:03:58 +0000103Each step of transforming code is encapsulated in a fixer. The command ``2to3
Benjamin Petersone0820e22009-02-07 23:01:19 +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
Benjamin Peterson0d19eaf2009-12-28 20:51:17 +0000125 Converts ``callable(x)`` to ``isinstance(x, collections.Callable)``, adding
Benjamin Peterson414ffa82011-10-24 08:51:15 -0400126 an import to :mod:`collections` if needed. Note ``callable(x)`` has returned
127 in Python 3.2, so if you do not intend to support Python 3.1, you can disable
128 this fixer.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000129
130.. 2to3fixer:: dict
131
132 Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to
133 :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and
Alexandre Vassalottib227f472010-01-12 18:25:33 +0000134 :meth:`dict.itervalues` to :meth:`dict.values`. Similarly,
Benjamin Peterson24055472010-03-20 16:17:37 +0000135 :meth:`dict.viewitems`, :meth:`dict.viewkeys` and :meth:`dict.viewvalues` are
136 converted respectively to :meth:`dict.items`, :meth:`dict.keys` and
Alexandre Vassalottib227f472010-01-12 18:25:33 +0000137 :meth:`dict.values`. It also wraps existing usages of :meth:`dict.items`,
138 :meth:`dict.keys`, and :meth:`dict.values` in a call to :class:`list`.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000139
140.. 2to3fixer:: except
141
142 Converts ``except X, T`` to ``except X as T``.
143
144.. 2to3fixer:: exec
145
146 Converts the :keyword:`exec` statement to the :func:`exec` function.
147
148.. 2to3fixer:: execfile
149
150 Removes usage of :func:`execfile`. The argument to :func:`execfile` is
151 wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`.
152
Benjamin Petersond47667c2010-03-20 16:16:44 +0000153.. 2to3fixer:: exitfunc
154
155 Changes assignment of :attr:`sys.exitfunc` to use of the :mod:`atexit`
156 module.
157
Benjamin Petersone0820e22009-02-07 23:01:19 +0000158.. 2to3fixer:: filter
159
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000160 Wraps :func:`filter` usage in a :class:`list` call.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000161
162.. 2to3fixer:: funcattrs
163
164 Fixes function attributes that have been renamed. For example,
165 ``my_function.func_closure`` is converted to ``my_function.__closure__``.
166
167.. 2to3fixer:: future
168
169 Removes ``from __future__ import new_feature`` statements.
170
171.. 2to3fixer:: getcwdu
172
173 Renames :func:`os.getcwdu` to :func:`os.getcwd`.
174
175.. 2to3fixer:: has_key
176
177 Changes ``dict.has_key(key)`` to ``key in dict``.
178
179.. 2to3fixer:: idioms
180
Georg Brandle83a4ad2009-03-13 19:03:58 +0000181 This optional fixer performs several transformations that make Python code
182 more idiomatic. Type comparisons like ``type(x) is SomeClass`` and
Benjamin Petersone0820e22009-02-07 23:01:19 +0000183 ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``.
184 ``while 1`` becomes ``while True``. This fixer also tries to make use of
Georg Brandle83a4ad2009-03-13 19:03:58 +0000185 :func:`sorted` in appropriate places. For example, this block ::
Benjamin Petersone0820e22009-02-07 23:01:19 +0000186
187 L = list(some_iterable)
188 L.sort()
189
190 is changed to ::
191
192 L = sorted(some_iterable)
193
194.. 2to3fixer:: import
195
196 Detects sibling imports and converts them to relative imports.
197
198.. 2to3fixer:: imports
199
200 Handles module renames in the standard library.
201
202.. 2to3fixer:: imports2
203
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000204 Handles other modules renames in the standard library. It is separate from
205 the :2to3fixer:`imports` fixer only because of technical limitations.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000206
207.. 2to3fixer:: input
208
209 Converts ``input(prompt)`` to ``eval(input(prompt))``
210
211.. 2to3fixer:: intern
212
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000213 Converts :func:`intern` to :func:`sys.intern`.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000214
215.. 2to3fixer:: isinstance
216
217 Fixes duplicate types in the second argument of :func:`isinstance`. For
218 example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x,
219 (int))``.
220
221.. 2to3fixer:: itertools_imports
222
223 Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and
224 :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also
225 changed to :func:`itertools.filterfalse`.
226
227.. 2to3fixer:: itertools
228
229 Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
Georg Brandld7d4fd72009-07-26 14:37:28 +0000230 :func:`itertools.imap` to their built-in equivalents.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000231 :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.
232
233.. 2to3fixer:: long
234
Raymond Hettingercec795d2011-07-14 14:41:43 +0800235 Strips the ``L`` suffix on long literals and renames :class:`long` to
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000236 :class:`int`.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000237
238.. 2to3fixer:: map
239
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000240 Wraps :func:`map` in a :class:`list` call. It also changes ``map(None, x)``
Benjamin Petersone0820e22009-02-07 23:01:19 +0000241 to ``list(x)``. Using ``from future_builtins import map`` disables this
242 fixer.
243
244.. 2to3fixer:: metaclass
245
246 Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class
247 body) to the new (``class X(metaclass=Meta)``).
248
249.. 2to3fixer:: methodattrs
250
251 Fixes old method attribute names. For example, ``meth.im_func`` is converted
252 to ``meth.__func__``.
253
254.. 2to3fixer:: ne
255
256 Converts the old not-equal syntax, ``<>``, to ``!=``.
257
258.. 2to3fixer:: next
259
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000260 Converts the use of iterator's :meth:`~iterator.next` methods to the
261 :func:`next` function. It also renames :meth:`next` methods to
262 :meth:`~object.__next__`.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000263
264.. 2to3fixer:: nonzero
265
266 Renames :meth:`~object.__nonzero__` to :meth:`~object.__bool__`.
267
Benjamin Petersonc5e68b12009-02-08 14:38:13 +0000268.. 2to3fixer:: numliterals
269
270 Converts octal literals into the new syntax.
271
Benjamin Petersone0820e22009-02-07 23:01:19 +0000272.. 2to3fixer:: paren
273
274 Add extra parenthesis where they are required in list comprehensions. For
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000275 example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000276
277.. 2to3fixer:: print
278
279 Converts the :keyword:`print` statement to the :func:`print` function.
280
Benjamin Peterson52a70c42010-07-01 17:45:52 +0000281.. 2to3fixer:: raise
Benjamin Petersone0820e22009-02-07 23:01:19 +0000282
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000283 Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise
Benjamin Petersone0820e22009-02-07 23:01:19 +0000284 E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be
285 incorrect because substituting tuples for exceptions has been removed in 3.0.
286
287.. 2to3fixer:: raw_input
288
289 Converts :func:`raw_input` to :func:`input`.
290
291.. 2to3fixer:: reduce
292
293 Handles the move of :func:`reduce` to :func:`functools.reduce`.
294
295.. 2to3fixer:: renames
296
297 Changes :data:`sys.maxint` to :data:`sys.maxsize`.
298
299.. 2to3fixer:: repr
300
301 Replaces backtick repr with the :func:`repr` function.
302
303.. 2to3fixer:: set_literal
304
305 Replaces use of the :class:`set` constructor with set literals. This fixer
306 is optional.
307
308.. 2to3fixer:: standard_error
309
310 Renames :exc:`StandardError` to :exc:`Exception`.
311
312.. 2to3fixer:: sys_exc
313
314 Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`,
315 :data:`sys.exc_traceback` to use :func:`sys.exc_info`.
316
317.. 2to3fixer:: throw
318
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000319 Fixes the API change in generator's :meth:`throw` method.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000320
321.. 2to3fixer:: tuple_params
322
323 Removes implicit tuple parameter unpacking. This fixer inserts temporary
324 variables.
325
326.. 2to3fixer:: types
327
328 Fixes code broken from the removal of some members in the :mod:`types`
329 module.
330
331.. 2to3fixer:: unicode
332
333 Renames :class:`unicode` to :class:`str`.
334
335.. 2to3fixer:: urllib
336
337 Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib`
338 package.
339
340.. 2to3fixer:: ws_comma
341
342 Removes excess whitespace from comma separated items. This fixer is
343 optional.
344
345.. 2to3fixer:: xrange
346
347 Renames :func:`xrange` to :func:`range` and wraps existing :func:`range`
348 calls with :class:`list`.
349
350.. 2to3fixer:: xreadlines
351
Benjamin Petersonb8e17f72009-02-08 15:14:57 +0000352 Changes ``for x in file.xreadlines()`` to ``for x in file``.
Benjamin Petersone0820e22009-02-07 23:01:19 +0000353
354.. 2to3fixer:: zip
355
356 Wraps :func:`zip` usage in a :class:`list` call. This is disabled when
357 ``from future_builtins import zip`` appears.
Benjamin Peterson40202212008-07-24 02:45:37 +0000358
359
Benjamin Peterson40202212008-07-24 02:45:37 +0000360:mod:`lib2to3` - 2to3's library
361-------------------------------
362
363.. module:: lib2to3
364 :synopsis: the 2to3 library
365.. moduleauthor:: Guido van Rossum
366.. moduleauthor:: Collin Winter
Benjamin Peterson2b42c292009-05-02 20:26:53 +0000367.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson40202212008-07-24 02:45:37 +0000368
Benjamin Peterson7f8f6602008-09-27 16:23:55 +0000369
Georg Brandl16a57f62009-04-27 15:29:09 +0000370.. note::
Benjamin Peterson7f8f6602008-09-27 16:23:55 +0000371
372 The :mod:`lib2to3` API should be considered unstable and may change
373 drastically in the future.
374
Benjamin Peterson40202212008-07-24 02:45:37 +0000375.. XXX What is the public interface anyway?