0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python モジュールの互換性を保つ方法

Last updated at Posted at 2021-07-03

はじめに

主な実行環境は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
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?