LoginSignup
57
21

More than 3 years have passed since last update.

Pythonでファイル名が悪くてimportでハマった

Last updated at Posted at 2020-04-30

ライブラリをちょっと試そうとして、import したいモジュールと同じ名前を付けてハマりました。常識なのかもしれませんが、知らなかったのでメモしておきます。

エラー

math モジュールを試したくて、math.py というファイルを書いたとします。

math.py
import math
print(math.pi)

これを実行するとエラーになります。

実行結果
$ python math.py
Traceback (most recent call last):
  File "math.py", line 1, in <module>
    import math
  File "/home/xxxx/math.py", line 2, in <module>
    print(math.pi)
AttributeError: partially initialized module 'math' has no attribute 'pi' (most likely due to a circular import)

自分自身を循環参照

原因はエラーに書いてあるように自分自身を import して循環してしまったことです。

(most likely due to a circular import)

すぐには分からなかったので、適当に print を入れたりしてみました。

math.py
print("math")
import math
print(math.pi)
実行結果
$ python math.py
math
math
Traceback (most recent call last):
  File "math.py", line 2, in <module>
    import math
  File "/home/xxxx/math.py", line 3, in <module>
    print(math.pi)
AttributeError: partially initialized module 'math' has no attribute 'pi' (most likely due to a circular import)

math が2回表示されています。これでようやく、自分自身を参照していることが分かりました。

同じファイルの2回目の import は無視されるので先に進んで、math.pi がないことからエラーになります。

結論

ファイル名を変えれば動きます。import の対象と同じファイル名は避けましょう。

57
21
3

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
57
21