はじめに
主な実行環境はPython3系を想定しています。
Pythonの互換性を保つ方法は様々ありますが、ここでは特にモジュールについての互換性の保ち方を記載します。
モジュールがインストールされていない環境との互換性
インストールされていなくても動作に大きく影響しないモジュールがインストールされていない場合に、そのモジュールをインストールせずとも動作可能にするには以下のようにする。
# not installed compatibility
try:
from tqdm import tqdm
except ImportError:
tqdm = lambda x:x
# example
for i in tqdm([1,2,3]):
print(i)
tqdmモジュールがインストールされていない場合、tqdm([1,2,3]) -> [1,2,3]
となり、プログレスバーは表示されないが、動作に支障はきたさない。
Python2系との互換性
機能はほぼ同じだが、名前が異なっているモジュールをインポートする。
# python version 2 compatibility
try:
from urllib.parse import unquote
except ImportError:
from urllib import unquote
メソッド名やクラス名が異なっている場合は、以下のようにas
を活用する。
try:
from A import B as C
except ImportError:
from D import E as C