5
8

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 5 years have passed since last update.

Python スクリプトで if __name__ == '__main__': を使うとどうなるか

5
Last updated at Posted at 2018-08-22

使わなかった場合

ファイル

module.py
def greet():
    print('hello')

greet()
main.py
import module

module.greet()
print('world')

実行結果

直接 module.py を実行した場合:

$ python module.py
hello

module.py で定義されている greet() を main.py で呼び出して利用した場合:

$ python main.py
hello
hello
world

main.py でモジュールをインポートしただけで greet() が実行されるので, hello が 2 回出力されてしまう.

イメージ

main+module.py
####### import module #######
def greet():
    print('hello')

greet() # これも展開される
# >hello
#############################

greet()
# >hello(2回目)
print('world')
# >world

使った場合

ファイル

module.py
def greet():
    print('hello')

if __name__ == '__main__':
    greet()
main.py
import module

module.greet()
print('world')

実行結果

$ python module.py
hello
$ python main.py
hello
world

main.py でモジュールをインポートしたときには greet() が実行されず,呼び出して初めて実行される.つまり, if __name__ == '__main__': 下の処理は,コンソールから直接実行されたときのみ実行され,メソッドとして参照された際には実行されない.

イメージ

main+module.py
####### import module #######
def greet():
    print('hello')

''' これは展開されない
if __name__ == '__main__':
    greet()
'''
#############################

greet()
# >hello
print('world')
# >world
5
8
2

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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?