1.. _2to3-reference: 2 32to3 --- Automated Python 2 to 3 code translation 4================================================= 5 6.. sectionauthor:: Benjamin Peterson <[email protected]> 7 82to3 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 10contains 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. 13 14.. deprecated-removed:: 3.11 3.13 15 The ``lib2to3`` module was marked pending for deprecation in Python 3.9 16 (raising :exc:`PendingDeprecationWarning` on import) and fully deprecated 17 in Python 3.11 (raising :exc:`DeprecationWarning`). The ``2to3`` tool is 18 part of that. It will be removed in Python 3.13. 19 20.. _2to3-using: 21 22Using 2to3 23---------- 24 252to3 will usually be installed with the Python interpreter as a script. It is 26also located in the :file:`Tools/scripts` directory of the Python root. 27 282to3's basic arguments are a list of files or directories to transform. The 29directories are recursively traversed for Python sources. 30 31Here is a sample Python 2.x source file, :file:`example.py`:: 32 33 def greet(name): 34 print "Hello, {0}!".format(name) 35 print "What's your name?" 36 name = raw_input() 37 greet(name) 38 39It can be converted to Python 3.x code via 2to3 on the command line: 40 41.. code-block:: shell-session 42 43 $ 2to3 example.py 44 45A diff against the original source file is printed. 2to3 can also write the 46needed modifications right back to the source file. (A backup of the original 47file is made unless :option:`!-n` is also given.) Writing the changes back is 48enabled with the :option:`!-w` flag: 49 50.. code-block:: shell-session 51 52 $ 2to3 -w example.py 53 54After transformation, :file:`example.py` looks like this:: 55 56 def greet(name): 57 print("Hello, {0}!".format(name)) 58 print("What's your name?") 59 name = input() 60 greet(name) 61 62Comments and exact indentation are preserved throughout the translation process. 63 64By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`. The 65:option:`!-l` flag lists all available fixers. An explicit set of fixers to run 66can be given with :option:`!-f`. Likewise the :option:`!-x` explicitly disables a 67fixer. The following example runs only the ``imports`` and ``has_key`` fixers: 68 69.. code-block:: shell-session 70 71 $ 2to3 -f imports -f has_key example.py 72 73This command runs every fixer except the ``apply`` fixer: 74 75.. code-block:: shell-session 76 77 $ 2to3 -x apply example.py 78 79Some fixers are *explicit*, meaning they aren't run by default and must be 80listed on the command line to be run. Here, in addition to the default fixers, 81the ``idioms`` fixer is run: 82 83.. code-block:: shell-session 84 85 $ 2to3 -f all -f idioms example.py 86 87Notice how passing ``all`` enables all default fixers. 88 89Sometimes 2to3 will find a place in your source code that needs to be changed, 90but 2to3 cannot fix automatically. In this case, 2to3 will print a warning 91beneath the diff for a file. You should address the warning in order to have 92compliant 3.x code. 93 942to3 can also refactor doctests. To enable this mode, use the :option:`!-d` 95flag. Note that *only* doctests will be refactored. This also doesn't require 96the module to be valid Python. For example, doctest like examples in a reST 97document could also be refactored with this option. 98 99The :option:`!-v` option enables output of more information on the translation 100process. 101 102Since some print statements can be parsed as function calls or statements, 2to3 103cannot always read files containing the print function. When 2to3 detects the 104presence of the ``from __future__ import print_function`` compiler directive, it 105modifies its internal grammar to interpret :func:`print` as a function. This 106change can also be enabled manually with the :option:`!-p` flag. Use 107:option:`!-p` to run fixers on code that already has had its print statements 108converted. Also :option:`!-e` can be used to make :func:`exec` a function. 109 110The :option:`!-o` or :option:`!--output-dir` option allows specification of an 111alternate directory for processed output files to be written to. The 112:option:`!-n` flag is required when using this as backup files do not make sense 113when not overwriting the input files. 114 115.. versionadded:: 3.2.3 116 The :option:`!-o` option was added. 117 118The :option:`!-W` or :option:`!--write-unchanged-files` flag tells 2to3 to always 119write output files even if no changes were required to the file. This is most 120useful with :option:`!-o` so that an entire Python source tree is copied with 121translation from one directory to another. 122This option implies the :option:`!-w` flag as it would not make sense otherwise. 123 124.. versionadded:: 3.2.3 125 The :option:`!-W` flag was added. 126 127The :option:`!--add-suffix` option specifies a string to append to all output 128filenames. The :option:`!-n` flag is required when specifying this as backups 129are not necessary when writing to different filenames. Example: 130 131.. code-block:: shell-session 132 133 $ 2to3 -n -W --add-suffix=3 example.py 134 135Will cause a converted file named ``example.py3`` to be written. 136 137.. versionadded:: 3.2.3 138 The :option:`!--add-suffix` option was added. 139 140To translate an entire project from one directory tree to another use: 141 142.. code-block:: shell-session 143 144 $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode 145 146 147.. _2to3-fixers: 148 149Fixers 150------ 151 152Each step of transforming code is encapsulated in a fixer. The command ``2to3 153-l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on 154and off individually. They are described here in more detail. 155 156 157.. 2to3fixer:: apply 158 159 Removes usage of :func:`apply`. For example ``apply(function, *args, 160 **kwargs)`` is converted to ``function(*args, **kwargs)``. 161 162.. 2to3fixer:: asserts 163 164 Replaces deprecated :mod:`unittest` method names with the correct ones. 165 166 ================================ ========================================== 167 From To 168 ================================ ========================================== 169 ``failUnlessEqual(a, b)`` :meth:`assertEqual(a, b) 170 <unittest.TestCase.assertEqual>` 171 ``assertEquals(a, b)`` :meth:`assertEqual(a, b) 172 <unittest.TestCase.assertEqual>` 173 ``failIfEqual(a, b)`` :meth:`assertNotEqual(a, b) 174 <unittest.TestCase.assertNotEqual>` 175 ``assertNotEquals(a, b)`` :meth:`assertNotEqual(a, b) 176 <unittest.TestCase.assertNotEqual>` 177 ``failUnless(a)`` :meth:`assertTrue(a) 178 <unittest.TestCase.assertTrue>` 179 ``assert_(a)`` :meth:`assertTrue(a) 180 <unittest.TestCase.assertTrue>` 181 ``failIf(a)`` :meth:`assertFalse(a) 182 <unittest.TestCase.assertFalse>` 183 ``failUnlessRaises(exc, cal)`` :meth:`assertRaises(exc, cal) 184 <unittest.TestCase.assertRaises>` 185 ``failUnlessAlmostEqual(a, b)`` :meth:`assertAlmostEqual(a, b) 186 <unittest.TestCase.assertAlmostEqual>` 187 ``assertAlmostEquals(a, b)`` :meth:`assertAlmostEqual(a, b) 188 <unittest.TestCase.assertAlmostEqual>` 189 ``failIfAlmostEqual(a, b)`` :meth:`assertNotAlmostEqual(a, b) 190 <unittest.TestCase.assertNotAlmostEqual>` 191 ``assertNotAlmostEquals(a, b)`` :meth:`assertNotAlmostEqual(a, b) 192 <unittest.TestCase.assertNotAlmostEqual>` 193 ================================ ========================================== 194 195.. 2to3fixer:: basestring 196 197 Converts :class:`basestring` to :class:`str`. 198 199.. 2to3fixer:: buffer 200 201 Converts :class:`buffer` to :class:`memoryview`. This fixer is optional 202 because the :class:`memoryview` API is similar but not exactly the same as 203 that of :class:`buffer`. 204 205.. 2to3fixer:: dict 206 207 Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to 208 :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and 209 :meth:`dict.itervalues` to :meth:`dict.values`. Similarly, 210 :meth:`dict.viewitems`, :meth:`dict.viewkeys` and :meth:`dict.viewvalues` are 211 converted respectively to :meth:`dict.items`, :meth:`dict.keys` and 212 :meth:`dict.values`. It also wraps existing usages of :meth:`dict.items`, 213 :meth:`dict.keys`, and :meth:`dict.values` in a call to :class:`list`. 214 215.. 2to3fixer:: except 216 217 Converts ``except X, T`` to ``except X as T``. 218 219.. 2to3fixer:: exec 220 221 Converts the ``exec`` statement to the :func:`exec` function. 222 223.. 2to3fixer:: execfile 224 225 Removes usage of :func:`execfile`. The argument to :func:`execfile` is 226 wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`. 227 228.. 2to3fixer:: exitfunc 229 230 Changes assignment of :attr:`sys.exitfunc` to use of the :mod:`atexit` 231 module. 232 233.. 2to3fixer:: filter 234 235 Wraps :func:`filter` usage in a :class:`list` call. 236 237.. 2to3fixer:: funcattrs 238 239 Fixes function attributes that have been renamed. For example, 240 ``my_function.func_closure`` is converted to ``my_function.__closure__``. 241 242.. 2to3fixer:: future 243 244 Removes ``from __future__ import new_feature`` statements. 245 246.. 2to3fixer:: getcwdu 247 248 Renames :func:`os.getcwdu` to :func:`os.getcwd`. 249 250.. 2to3fixer:: has_key 251 252 Changes ``dict.has_key(key)`` to ``key in dict``. 253 254.. 2to3fixer:: idioms 255 256 This optional fixer performs several transformations that make Python code 257 more idiomatic. Type comparisons like ``type(x) is SomeClass`` and 258 ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``. 259 ``while 1`` becomes ``while True``. This fixer also tries to make use of 260 :func:`sorted` in appropriate places. For example, this block :: 261 262 L = list(some_iterable) 263 L.sort() 264 265 is changed to :: 266 267 L = sorted(some_iterable) 268 269.. 2to3fixer:: import 270 271 Detects sibling imports and converts them to relative imports. 272 273.. 2to3fixer:: imports 274 275 Handles module renames in the standard library. 276 277.. 2to3fixer:: imports2 278 279 Handles other modules renames in the standard library. It is separate from 280 the :2to3fixer:`imports` fixer only because of technical limitations. 281 282.. 2to3fixer:: input 283 284 Converts ``input(prompt)`` to ``eval(input(prompt))``. 285 286.. 2to3fixer:: intern 287 288 Converts :func:`intern` to :func:`sys.intern`. 289 290.. 2to3fixer:: isinstance 291 292 Fixes duplicate types in the second argument of :func:`isinstance`. For 293 example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x, 294 int)`` and ``isinstance(x, (int, float, int))`` is converted to 295 ``isinstance(x, (int, float))``. 296 297.. 2to3fixer:: itertools_imports 298 299 Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and 300 :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also 301 changed to :func:`itertools.filterfalse`. 302 303.. 2to3fixer:: itertools 304 305 Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and 306 :func:`itertools.imap` to their built-in equivalents. 307 :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`. 308 309.. 2to3fixer:: long 310 311 Renames :class:`long` to :class:`int`. 312 313.. 2to3fixer:: map 314 315 Wraps :func:`map` in a :class:`list` call. It also changes ``map(None, x)`` 316 to ``list(x)``. Using ``from future_builtins import map`` disables this 317 fixer. 318 319.. 2to3fixer:: metaclass 320 321 Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class 322 body) to the new (``class X(metaclass=Meta)``). 323 324.. 2to3fixer:: methodattrs 325 326 Fixes old method attribute names. For example, ``meth.im_func`` is converted 327 to ``meth.__func__``. 328 329.. 2to3fixer:: ne 330 331 Converts the old not-equal syntax, ``<>``, to ``!=``. 332 333.. 2to3fixer:: next 334 335 Converts the use of iterator's :meth:`~iterator.next` methods to the 336 :func:`next` function. It also renames :meth:`next` methods to 337 :meth:`~iterator.__next__`. 338 339.. 2to3fixer:: nonzero 340 341 Renames definitions of methods called :meth:`__nonzero__` 342 to :meth:`~object.__bool__`. 343 344.. 2to3fixer:: numliterals 345 346 Converts octal literals into the new syntax. 347 348.. 2to3fixer:: operator 349 350 Converts calls to various functions in the :mod:`operator` module to other, 351 but equivalent, function calls. When needed, the appropriate ``import`` 352 statements are added, e.g. ``import collections.abc``. The following mapping 353 are made: 354 355 ================================== ============================================= 356 From To 357 ================================== ============================================= 358 ``operator.isCallable(obj)`` ``callable(obj)`` 359 ``operator.sequenceIncludes(obj)`` ``operator.contains(obj)`` 360 ``operator.isSequenceType(obj)`` ``isinstance(obj, collections.abc.Sequence)`` 361 ``operator.isMappingType(obj)`` ``isinstance(obj, collections.abc.Mapping)`` 362 ``operator.isNumberType(obj)`` ``isinstance(obj, numbers.Number)`` 363 ``operator.repeat(obj, n)`` ``operator.mul(obj, n)`` 364 ``operator.irepeat(obj, n)`` ``operator.imul(obj, n)`` 365 ================================== ============================================= 366 367.. 2to3fixer:: paren 368 369 Add extra parenthesis where they are required in list comprehensions. For 370 example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``. 371 372.. 2to3fixer:: print 373 374 Converts the ``print`` statement to the :func:`print` function. 375 376.. 2to3fixer:: raise 377 378 Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise 379 E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be 380 incorrect because substituting tuples for exceptions has been removed in 3.0. 381 382.. 2to3fixer:: raw_input 383 384 Converts :func:`raw_input` to :func:`input`. 385 386.. 2to3fixer:: reduce 387 388 Handles the move of :func:`reduce` to :func:`functools.reduce`. 389 390.. 2to3fixer:: reload 391 392 Converts :func:`reload` to :func:`importlib.reload`. 393 394.. 2to3fixer:: renames 395 396 Changes :data:`sys.maxint` to :data:`sys.maxsize`. 397 398.. 2to3fixer:: repr 399 400 Replaces backtick repr with the :func:`repr` function. 401 402.. 2to3fixer:: set_literal 403 404 Replaces use of the :class:`set` constructor with set literals. This fixer 405 is optional. 406 407.. 2to3fixer:: standarderror 408 409 Renames :exc:`StandardError` to :exc:`Exception`. 410 411.. 2to3fixer:: sys_exc 412 413 Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`, 414 :data:`sys.exc_traceback` to use :func:`sys.exc_info`. 415 416.. 2to3fixer:: throw 417 418 Fixes the API change in generator's :meth:`throw` method. 419 420.. 2to3fixer:: tuple_params 421 422 Removes implicit tuple parameter unpacking. This fixer inserts temporary 423 variables. 424 425.. 2to3fixer:: types 426 427 Fixes code broken from the removal of some members in the :mod:`types` 428 module. 429 430.. 2to3fixer:: unicode 431 432 Renames :class:`unicode` to :class:`str`. 433 434.. 2to3fixer:: urllib 435 436 Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib` 437 package. 438 439.. 2to3fixer:: ws_comma 440 441 Removes excess whitespace from comma separated items. This fixer is 442 optional. 443 444.. 2to3fixer:: xrange 445 446 Renames :func:`xrange` to :func:`range` and wraps existing :func:`range` 447 calls with :class:`list`. 448 449.. 2to3fixer:: xreadlines 450 451 Changes ``for x in file.xreadlines()`` to ``for x in file``. 452 453.. 2to3fixer:: zip 454 455 Wraps :func:`zip` usage in a :class:`list` call. This is disabled when 456 ``from future_builtins import zip`` appears. 457 458 459:mod:`lib2to3` --- 2to3's library 460--------------------------------- 461 462.. module:: lib2to3 463 :synopsis: The 2to3 library 464 465.. moduleauthor:: Guido van Rossum 466.. moduleauthor:: Collin Winter 467.. moduleauthor:: Benjamin Peterson <[email protected]> 468 469**Source code:** :source:`Lib/lib2to3/` 470 471-------------- 472 473.. deprecated-removed:: 3.11 3.13 474 Python 3.9 switched to a PEG parser (see :pep:`617`) while lib2to3 is 475 using a less flexible LL(1) parser. Python 3.10 includes new language 476 syntax that is not parsable by lib2to3's LL(1) parser (see :pep:`634`). 477 The ``lib2to3`` module was marked pending for deprecation in Python 3.9 478 (raising :exc:`PendingDeprecationWarning` on import) and fully deprecated 479 in Python 3.11 (raising :exc:`DeprecationWarning`). 480 It will be removed from the standard library in Python 3.13. 481 Consider third-party alternatives such as `LibCST`_ or `parso`_. 482 483.. note:: 484 485 The :mod:`lib2to3` API should be considered unstable and may change 486 drastically in the future. 487 488.. _LibCST: https://libcst.readthedocs.io/ 489.. _parso: https://parso.readthedocs.io/ 490