0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【if __name__ == "__main__": 】の意味

Last updated at Posted at 2025-10-12

if __name__ == "__main__": の動作】

if __name__ == "__main__": の中 → そのスクリプトを直実行のときだけ実行される。
if __name__ == "__main__": の外 → そのスクリプトを、他のスクリプトからインポートしたときも実行される。

スクリプト内容

test1.py
def hello():
    print("こんにちは")

def bye(): 
    print("さよなら")

hello()

if __name__ == "__main__":
    bye()
test2.py
import test1
test3.py
import test1

test1.bye()

実行結果

(py_env) PS C:\tmp\py_script> py .\test1.py
こんにちは
さよなら
(py_env) PS C:\tmp\py_script> py .\test2.py
こんにちは
(py_env) PS C:\tmp\py_script> py .\test3.py
こんにちは
さよなら

__name__ とは?】

Python がスクリプトを読み込むときに、自動的に定義される特別な変数

  • (A) スクリプトを 直接実行 したとき →
    __name__"__main__" にセットされる。
  • (B) スクリプトを import したとき →
    __name__モジュール名(ファイル名) になる。

つまり、(A)の場合のみ"if"の結果がTrueになり、 if __name__ == "__main__"内が実行される。

【なぜこの仕組みがあるのか?】

この構文は、

  • 「スクリプトとしても使えるし、モジュールとしても使える」 ようにするための仕組み

Python では、ファイルを 「モジュール」 として他のファイルから import できるため、
if __name__ == "__main__": がないと、import しただけで意図せず実行されてしまう。


0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?