blob: 7fbfd51b0797c2b12c745a5fc9a838df67cb7388 [file] [log] [blame]
Benjamin Peterson40202212008-07-24 02:45:37 +00001.. _2to3-reference:
2
32to3 - Automated Python 2 to 3 code translation
4===============================================
5
Georg Brandl686d53e2009-01-14 00:08:09 +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
Georg Brandl27e87232009-10-27 13:31: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 Brandl40e15ed2009-04-05 21:48:06 +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
Georg Brandl4aef7032008-11-07 08:56:27 +000055Comments and exact indentation are preserved throughout the translation process.
Benjamin Peterson40202212008-07-24 02:45:37 +000056
Georg Brandl27e87232009-10-27 13:31: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
Georg Brandl4aef7032008-11-07 08:56:27 +000064This command runs every fixer except the ``apply`` fixer::
65
66 $ 2to3 -x apply example.py
67
Fred Drake23681da2008-10-24 02:28:15 +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
Georg Brandl4aef7032008-11-07 08:56:27 +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
Georg Brandl4aef7032008-11-07 08:56:27 +000086The :option:`-v` option enables output of more information on the translation
87process.
Benjamin Peterson15ad6c02008-09-04 23:31:27 +000088
Benjamin Peterson40202212008-07-24 02:45:37 +000089
Georg Brandl27e87232009-10-27 13:31:19 +000090.. _2to3-fixers:
91
92Fixers
93------
94
95Each step of tranforming code is encapsulated in a fixer. The command ``2to3
96-l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on
97and off individually. They are described here in more detail.
98
99
100.. 2to3fixer:: apply
101
102 Removes usage of :func:`apply`. For example ``apply(function, *args,
103 **kwargs)`` is converted to ``function(*args, **kwargs)``.
104
105.. 2to3fixer:: basestring
106
107 Converts :class:`basestring` to :class:`str`.
108
109.. 2to3fixer:: buffer
110
111 Converts :class:`buffer` to :class:`memoryview`. This fixer is optional
112 because the :class:`memoryview` API is similar but not exactly the same as
113 that of :class:`buffer`.
114
115.. 2to3fixer:: callable
116
117 Converts ``callable(x)`` to ``hasattr(x, "__call_")``.
118
119.. 2to3fixer:: dict
120
121 Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to
122 :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and
123 :meth:`dict.itervalues` to :meth:`dict.values`. It also wraps existing
124 usages of :meth:`dict.items`, :meth:`dict.keys`, and :meth:`dict.values` in a
125 call to :class:`list`.
126
127.. 2to3fixer:: except
128
129 Converts ``except X, T`` to ``except X as T``.
130
131.. 2to3fixer:: exec
132
133 Converts the :keyword:`exec` statement to the :func:`exec` function.
134
135.. 2to3fixer:: execfile
136
137 Removes usage of :func:`execfile`. The argument to :func:`execfile` is
138 wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`.
139
140.. 2to3fixer:: filter
141
142 Wraps :func:`filter` usage in a :class:`list` call.
143
144.. 2to3fixer:: funcattrs
145
146 Fixes function attributes that have been renamed. For example,
147 ``my_function.func_closure`` is converted to ``my_function.__closure__``.
148
149.. 2to3fixer:: future
150
151 Removes ``from __future__ import new_feature`` statements.
152
153.. 2to3fixer:: getcwdu
154
155 Renames :func:`os.getcwdu` to :func:`os.getcwd`.
156
157.. 2to3fixer:: has_key
158
159 Changes ``dict.has_key(key)`` to ``key in dict``.
160
161.. 2to3fixer:: idioms
162
163 This optional fixer preforms several transformations that make Python code
164 more idiomatic. Type comparisions like ``type(x) is SomeClass`` and
165 ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``.
166 ``while 1`` becomes ``while True``. This fixer also tries to make use of
167 :func:`sorted` in appropiate places. For example, this block ::
168
169 L = list(some_iterable)
170 L.sort()
171
172 is changed to ::
173
174 L = sorted(some_iterable)
175
176.. 2to3fixer:: import
177
178 Detects sibling imports and converts them to relative imports.
179
180.. 2to3fixer:: imports
181
182 Handles module renames in the standard library.
183
184.. 2to3fixer:: imports2
185
186 Handles other modules renames in the standard library. It is separate from
187 the :2to3fixer:`imports` fixer only because of technical limitations.
188
189.. 2to3fixer:: input
190
191 Converts ``input(prompt)`` to ``eval(input(prompt))``
192
193.. 2to3fixer:: intern
194
195 Converts :func:`intern` to :func:`sys.intern`.
196
197.. 2to3fixer:: isinstance
198
199 Fixes duplicate types in the second argument of :func:`isinstance`. For
200 example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x,
201 (int))``.
202
203.. 2to3fixer:: itertools_imports
204
205 Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and
206 :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also
207 changed to :func:`itertools.filterfalse`.
208
209.. 2to3fixer:: itertools
210
211 Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
Georg Brandl4ae4f872009-10-27 14:37:48 +0000212 :func:`itertools.imap` to their built-in equivalents.
Georg Brandl27e87232009-10-27 13:31:19 +0000213 :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.
214
215.. 2to3fixer:: long
216
217 Strips the ``L`` prefix on long literals and renames :class:`long` to
218 :class:`int`.
219
220.. 2to3fixer:: map
221
222 Wraps :func:`map` in a :class:`list` call. It also changes ``map(None, x)``
223 to ``list(x)``. Using ``from future_builtins import map`` disables this
224 fixer.
225
226.. 2to3fixer:: metaclass
227
228 Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class
229 body) to the new (``class X(metaclass=Meta)``).
230
231.. 2to3fixer:: methodattrs
232
233 Fixes old method attribute names. For example, ``meth.im_func`` is converted
234 to ``meth.__func__``.
235
236.. 2to3fixer:: ne
237
238 Converts the old not-equal syntax, ``<>``, to ``!=``.
239
240.. 2to3fixer:: next
241
Georg Brandl0dfdf002009-10-27 14:36:50 +0000242 Converts the use of iterator's :meth:`~iterator.next` methods to the
243 :func:`next` function. It also renames :meth:`next` methods to
244 :meth:`~object.__next__`.
Georg Brandl27e87232009-10-27 13:31:19 +0000245
246.. 2to3fixer:: nonzero
247
248 Renames :meth:`~object.__nonzero__` to :meth:`~object.__bool__`.
249
250.. 2to3fixer:: numliterals
251
252 Converts octal literals into the new syntax.
253
254.. 2to3fixer:: paren
255
256 Add extra parenthesis where they are required in list comprehensions. For
257 example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``.
258
259.. 2to3fixer:: print
260
261 Converts the :keyword:`print` statement to the :func:`print` function.
262
263.. 2to3fixer:: raises
264
265 Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise
266 E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be
267 incorrect because substituting tuples for exceptions has been removed in 3.0.
268
269.. 2to3fixer:: raw_input
270
271 Converts :func:`raw_input` to :func:`input`.
272
273.. 2to3fixer:: reduce
274
275 Handles the move of :func:`reduce` to :func:`functools.reduce`.
276
277.. 2to3fixer:: renames
278
279 Changes :data:`sys.maxint` to :data:`sys.maxsize`.
280
281.. 2to3fixer:: repr
282
283 Replaces backtick repr with the :func:`repr` function.
284
285.. 2to3fixer:: set_literal
286
287 Replaces use of the :class:`set` constructor with set literals. This fixer
288 is optional.
289
290.. 2to3fixer:: standard_error
291
292 Renames :exc:`StandardError` to :exc:`Exception`.
293
294.. 2to3fixer:: sys_exc
295
296 Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`,
297 :data:`sys.exc_traceback` to use :func:`sys.exc_info`.
298
299.. 2to3fixer:: throw
300
301 Fixes the API change in generator's :meth:`throw` method.
302
303.. 2to3fixer:: tuple_params
304
305 Removes implicit tuple parameter unpacking. This fixer inserts temporary
306 variables.
307
308.. 2to3fixer:: types
309
310 Fixes code broken from the removal of some members in the :mod:`types`
311 module.
312
313.. 2to3fixer:: unicode
314
315 Renames :class:`unicode` to :class:`str`.
316
317.. 2to3fixer:: urllib
318
319 Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib`
320 package.
321
322.. 2to3fixer:: ws_comma
323
324 Removes excess whitespace from comma separated items. This fixer is
325 optional.
326
327.. 2to3fixer:: xrange
328
329 Renames :func:`xrange` to :func:`range` and wraps existing :func:`range`
330 calls with :class:`list`.
331
332.. 2to3fixer:: xreadlines
333
334 Changes ``for x in file.xreadlines()`` to ``for x in file``.
335
336.. 2to3fixer:: zip
337
338 Wraps :func:`zip` usage in a :class:`list` call. This is disabled when
339 ``from future_builtins import zip`` appears.
340
341
Benjamin Peterson40202212008-07-24 02:45:37 +0000342:mod:`lib2to3` - 2to3's library
343-------------------------------
344
345.. module:: lib2to3
346 :synopsis: the 2to3 library
347.. moduleauthor:: Guido van Rossum
348.. moduleauthor:: Collin Winter
Georg Brandl20f2ee92009-10-27 14:10:28 +0000349.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson40202212008-07-24 02:45:37 +0000350
Benjamin Peterson7f8f6602008-09-27 16:23:55 +0000351
Georg Brandl38853142009-04-28 18:23:28 +0000352.. note::
Benjamin Peterson7f8f6602008-09-27 16:23:55 +0000353
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?