How to port Python 2 Code to Python 3

author

Brett Cannon

概要

Python 2 reached its official end-of-life at the start of 2020. This means that no new bug reports, fixes, or changes will be made to Python 2 - it's no longer supported.

This guide is intended to provide you with a path to Python 3 for your code, that includes compatibility with Python 2 as a first step.

もしあなたが標準 Python ライブラリではなく拡張ライブラリでの移植手段を探しているならば Python 3 への拡張モジュール移植 を参照してください。

The archived python-porting mailing list may contain some useful guidance.

短い説明

To achieve Python 2/3 compatibility in a single code base, the basic steps are:

  1. Python 2.7 だけをサポートすることに気を配ってください。

  2. Make sure you have good test coverage (coverage.py can help; python -m pip install coverage)

  3. Learn the differences between Python 2 and 3

  4. Use Futurize (or Modernize) to update your code (e.g. python -m pip install future)

  5. Use Pylint to help make sure you don't regress on your Python 3 support (python -m pip install pylint)

  6. Use caniusepython3 to find out which of your dependencies are blocking your use of Python 3 (python -m pip install caniusepython3)

  7. Once your dependencies are no longer blocking you, use continuous integration to make sure you stay compatible with Python 2 and 3 (tox can help test against multiple versions of Python; python -m pip install tox)

  8. Consider using optional static type checking to make sure your type usage works in both Python 2 and 3 (e.g. use mypy to check your typing under both Python 2 and Python 3; python -m pip install mypy).

注釈

Note: Using python -m pip install guarantees that the pip you invoke is the one installed for the Python currently in use, whether it be a system-wide pip or one installed within a virtual environment.

詳細

Even if other factors - say, dependencies over which you have no control - still require you to support Python 2, that does not prevent you taking the step of including Python 3 support.

Most changes required to support Python 3 lead to cleaner code using newer practices even in Python 2 code.

Different versions of Python 2

Ideally, your code should be compatible with Python 2.7, which was the last supported version of Python 2.

Some of the tools mentioned in this guide will not work with Python 2.6.

If absolutely necessary, the six project can help you support Python 2.5 and 3 simultaneously. Do realize, though, that nearly all the projects listed in this guide will not be available to you.

If you are able to skip Python 2.5 and older, the required changes to your code will be minimal. At worst you will have to use a function instead of a method in some instances or have to import a function instead of using a built-in one.

あなたの setup.py ファイルに、相応しいサポートバージョンを明記することを忘れないこと

setup.py ファイルに、あなたがサポートする Python バージョンを Trove 分類 で正しく明記すべきです。あなたのプロジェクトはまだ Python 3 をサポートしていないので、少なくとも Programming Language :: Python :: 2 :: Only と明記すべきです。理想的には Python のメジャー/マイナーバージョンも指定すべきです。例えば Programming Language :: Python :: 2.7 のように。

良いテストカバレッジを確保する。

そうしたい一番古いバージョンの Python 2 をサポート出来ているならば、あなたのテストスイートが十分な網羅性かを確認したいでしょう。あなたのコードをツールで書き換えた後に現れるあらゆる失敗が実際にはツールのバグで、あなたのコードのバグではないとするのに十分なだけの確信をあなたのテストスイートに持ちたいならば、良い経験則がこれです。目標とする数値で言えば、80% 以上の網羅性を目指してみてください (そしてカバレッジ 90% を越えるのが難しかったとしても気に病む必要はありません)。テストカバレッジの計測ツールを手持ちでないならば、 coverage.py がお奨めです。

Be aware of the differences between Python 2 and 3

Once you have your code well-tested you are ready to begin porting your code to Python 3! But to fully understand how your code is going to change and what you want to look out for while you code, you will want to learn what changes Python 3 makes in terms of Python 2.

Some resources for understanding the differences and their implications for you code:

コードをアップデートする。

There are tools available that can port your code automatically.

Futurize does its best to make Python 3 idioms and practices exist in Python 2, e.g. backporting the bytes type from Python 3 so that you have semantic parity between the major versions of Python. This is the better approach for most cases.

Modernize, on the other hand, is more conservative and targets a Python 2/3 subset of Python, directly relying on six to help provide compatibility.

A good approach is to run the tool over your test suite first and visually inspect the diff to make sure the transformation is accurate. After you have transformed your test suite and verified that all the tests still pass as expected, then you can transform your application code knowing that any tests which fail is a translation failure.

Unfortunately the tools can't automate everything to make your code work under Python 3, and you will also need to read the tools' documentation in case some options you need are turned off by default.

Key issues to be aware of and check for:

除算

In Python 3, 5 / 2 == 2.5 and not 2 as it was in Python 2; all division between int values result in a float. This change has actually been planned since Python 2.2 which was released in 2002. Since then users have been encouraged to add from __future__ import division to any and all files which use the / and // operators or to be running the interpreter with the -Q flag. If you have not been doing this then you will need to go through your code and do two things:

  1. from __future__ import division をあなたのファイルに追加します

  2. floor division (訳注: float での結果に floor() 適用したのと同じ振る舞いをする除算) に対しては // を、浮動小数点数の演算を期待する箇所ではそのまま / を使うように、除算演算子を必要に応じて変更します。

オブジェクトが自身の __truediv__ メソッドを持っているのに __floordiv__ を持っていない場合に壊れてしまうので、 /// に単純に自動的に変換することは出来ません(例えばユーザ定義クラスで / を何かの演算に使っていて、 // は同じ事をしないか何もしないような場合)。

テキスト対バイナリデータ

Python 2 では str 型をテキストとバイナリデータのどちらにも使うことが出来ていました。不幸なことにこれは、2 つの異なる概念を重ね合わせていて、両方の種類のデータに対して、時々動作して時々はそうではない、といった傷つきやすいコードに繋がりやすいものでした。人々が特定の一つの型の代わりに str を受け付ける何かが、それが許容するのはテキストなのかバイナリデータなのかを名言しないときの、悩ましい API を生み出してしまう要因でもありました。これはとりわけマルチリンガルをサポートするための状況を、テキストデータをサポートしていると主張しているのに明示的に unicode をサポートすることに注意を払わない API、という形で複雑にしていました。

Python 3 made text and binary data distinct types that cannot simply be mixed together. For any code that deals only with text or only binary data, this separation doesn't pose an issue. But for code that has to deal with both, it does mean you might have to now care about when you are using text compared to binary data, which is why this cannot be entirely automated.

Decide which APIs take text and which take binary (it is highly recommended you don't design APIs that can take both due to the difficulty of keeping the code working; as stated earlier it is difficult to do well). In Python 2 this means making sure the APIs that take text can work with unicode and those that work with binary data work with the bytes type from Python 3 (which is a subset of str in Python 2 and acts as an alias for bytes type in Python 2). Usually the biggest issue is realizing which methods exist on which types in Python 2 and 3 simultaneously (for text that's unicode in Python 2 and str in Python 3, for binary that's str/bytes in Python 2 and bytes in Python 3).

The following table lists the unique methods of each data type across Python 2 and 3 (e.g., the decode() method is usable on the equivalent binary data type in either Python 2 or 3, but it can't be used by the textual data type consistently between Python 2 and 3 because str in Python 3 doesn't have the method). Do note that as of Python 3.5 the __mod__ method was added to the bytes type.

テキストデータ

バイナリデータ

decode

encode

format

isdecimal

isnumeric

処理の区別を簡単にするには、バイナリデータとテキストの間のエンコードとデコードを、あなたのコードの境界で行うようにすることです。バイナリデータとしてテキストを受け取ったならば、即座にデコード。テキストをバイナリデータにして送信する必要があったら、出来るだけあとでエンコード。このようにすることで、あなたのコードは内部的にはテキストだけで動作し、ですから、今処理しているのがどの型なのかを逐一追跡しなくても良くなります。

The next issue is making sure you know whether the string literals in your code represent text or binary data. You should add a b prefix to any literal that presents binary data. For text you should add a u prefix to the text literal. (There is a __future__ import to force all unspecified literals to be Unicode, but usage has shown it isn't as effective as adding a b or u prefix to all literals explicitly)

You also need to be careful about opening files. Possibly you have not always bothered to add the b mode when opening a binary file (e.g., rb for binary reading). Under Python 3, binary files and text files are clearly distinct and mutually incompatible; see the io module for details. Therefore, you must make a decision of whether a file will be used for binary access (allowing binary data to be read and/or written) or textual access (allowing text data to be read and/or written). You should also use io.open() for opening files instead of the built-in open() function as the io module is consistent from Python 2 to 3 while the built-in open() function is not (in Python 3 it's actually io.open()). Do not bother with the outdated practice of using codecs.open() as that's only necessary for keeping compatibility with Python 2.5.

The constructors of both str and bytes have different semantics for the same arguments between Python 2 and 3. Passing an integer to bytes in Python 2 will give you the string representation of the integer: bytes(3) == '3'. But in Python 3, an integer argument to bytes will give you a bytes object as long as the integer specified, filled with null bytes: bytes(3) == b'\x00\x00\x00'. A similar worry is necessary when passing a bytes object to str. In Python 2 you just get the bytes object back: str(b'3') == b'3'. But in Python 3 you get the string representation of the bytes object: str(b'3') == "b'3'".

最後に、バイナリデータに対するインデクシングには取り扱いに注意が必要です(スライシングには特別な取り扱いは 不要 です)。Python 2 では、 b'123'[1] == b'2' ですが、Python 3 では b'123'[1] == 50 です。バイナリデータはただのバイナリ数値の羅列ですから、Python 3 では指示した位置のバイトの整数値を返します。ですが Python 2 の場合、 bytes == str であるために、インデクシングは bytes の要素一つを取り出すスライスとして振舞います。 six プロジェクトには six.indexbytes() と名付けられた関数があって、これは Python 3 がそうするように整数値を返します: six.indexbytes(b'123', 1)

まとめると、以下のようになります:

  1. どの API がテキストデータを受付け、どの API がバイナリデータを受け付けるのかを決めてください。

  2. あなたのコードが Python 2 で確実に、テキストで動くものは unicode でも動くように、バイナリデータで動くものは bytes でも動くようにしてください(どのメソッドがそれぞれの型で使えないのかを示した上記テーブルをみてください)。

  3. Mark all binary literals with a b prefix, textual literals with a u prefix

  4. バイナリデータをテキストにデコードするのは出来るだけ早く、テキストデータをバイナリデータにエンコードするのは出来るだけ遅く。

  5. ファイルは io.open() を使って開き、そうすべきときには必ず b モードを指定してください。

  6. Be careful when indexing into binary data

バージョン検出ではなく機能検出を使う

Inevitably you will have code that has to choose what to do based on what version of Python is running. The best way to do this is with feature detection of whether the version of Python you're running under supports what you need. If for some reason that doesn't work then you should make the version check be against Python 2 and not Python 3. To help explain this, let's look at an example.

Let's pretend that you need access to a feature of importlib that is available in Python's standard library since Python 3.3 and available for Python 2 through importlib2 on PyPI. You might be tempted to write code to access e.g. the importlib.abc module by doing the following:

import sys

if sys.version_info[0] == 3:
    from importlib import abc
else:
    from importlib2 import abc

このコードの問題は、 Python 4 が出たときに起きます。 Python 3 ではなく Python 2 を例外的なケースとして扱い、将来の Python のバージョンは Python 2 よりも Python 3 と互換性があると仮定する方が良さそうです:

import sys

if sys.version_info[0] > 2:
    from importlib import abc
else:
    from importlib2 import abc

ところが、最適解はバージョン検出を一切せずに、代わりに機能検出に頼ることです。 機能検出を使うことで、バージョン検出が上手く行かなくなる潜在的な問題を避けられ、機能の互換性を保つ助けになります:

try:
    from importlib import abc
except ImportError:
    from importlib2 import abc

互換性オプション

あなたのコードを完全に Python 3 互換に変換できたら、今度は Python 3 での動作が退化したり止まってしまうことがないようにしたいでしょう。この時点ではまだ実際に Python 3 で動作させられない阻害要因となる依存物を持っている場合に、これは特に当てはまります。

互換性を保ち続けるために、あなたが作る全ての新しいモジュールは、最低でもソースコードの先頭に以下のコードブロックを持つべきです:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

実行時に種々の互換性問題を警告してもらうために Python 2 を -3 フラグ付きで実行することも出来ます。 -Werror にすれば警告ではなくエラーになるので、うっかり警告を見逃すことがなくなります。

Pylint プロジェクトとその --py3k フラグを使って、Python 3 互換性から乖離し始めている際の警告を受け取ることも出来ます。これにより、 ModernizeFuturize を普通に実行してみて互換性を失っていないかを確認する、という必要がなくなります。この場合 Python 2.7 と Python 3.4 以上だけのサポートにすることが必要になります。それが Pylint がサポートする最小の Python バージョンだからです。

どの依存性があなたの移行を阻んでいるのかチェックする

After you have made your code compatible with Python 3 you should begin to care about whether your dependencies have also been ported. The caniusepython3 project was created to help you determine which projects -- directly or indirectly -- are blocking you from supporting Python 3. There is both a command-line tool as well as a web interface at https://caniusepython3.com.

このプロジェクトは同時にあなたのテストスイートに組み込むことが出来る、もう Python 3 使用を妨げる依存物がなくなった時点で失敗するテストコードも提供しています。これにより、Python 3 での動作を開始する際に、依存物を手動でチェックすることなく即座に気付くことが出来ます。

あなたの setup.py ファイルを更新して Python 3 互換を謳う

あなたのコードが Python 3 で動作するようになったら、 setup.py の classifiers を Programming Language :: Python :: 3 を含めるように更新して、Python 2 だけのサポートではないことを明記すべきです。これによって、あなたのコードを利用する人はあなたが Python 2 3 をサポートすることを知ることが出来ます。理想的には、今サポートしている Python のメジャー/マイナーバージョンも classifiers に追加したいでしょう。

継続的インテグレーションを使って互換性を維持し続ける。

Once you are able to fully run under Python 3 you will want to make sure your code always works under both Python 2 and 3. Probably the best tool for running your tests under multiple Python interpreters is tox. You can then integrate tox with your continuous integration system so that you never accidentally break Python 2 or 3 support.

Python 3 インタプリタで -bb フラグを使って、 bytes と string 、もしくは bytes と int を比較したときに例外を引き起こしたいと思うでしょう (後者は Python 3.5 から使えます)。 デフォルトでは型の異なる比較は単純に False を返しますが、テキスト/バイナリデータ処理の分離を誤ったり、バイト列への添え字操作を誤ると、簡単には間違いを見つけられません。 このフラグはそれが起こった場合に例外を起こすことで、その種のケースを追跡する助けになります。

Consider using optional static type checking

Another way to help port your code is to use a static type checker like mypy or pytype on your code. These tools can be used to analyze your code as if it's being run under Python 2, then you can run the tool a second time as if your code is running under Python 3. By running a static type checker twice like this you can discover if you're e.g. misusing binary data type in one version of Python compared to another. If you add optional type hints to your code you can also explicitly state whether your APIs use textual or binary data, helping to make sure everything functions as expected in both versions of Python.