1
5

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_ __name__, __main__

Last updated at Posted at 2021-11-28

実行スクリプト上での__name____main__になる

my_module.py
def print_name():
    print(__name__)


print_name()
$ python my_module.py
__main__

moduleとして呼び出した時の__name__はmodule名になる

moduleをimportしたときにmoduleを全て一度実行するので、my_moduleが3回printされている。

main.py
import my_module

my_module.print_name()
print(my_module.__name__)
print(__name__)
$ python main.py
my_module
my_module
my_module
__main__

moduleをimportして使用するときに実行したくない処理はif __name__ == "__main__":の中に入れる

my_module.py
def print_name():
    print(__name__)


if __name__ == "__main__"
    print_name()
main.py
import my_module

my_module.print_name()
print(my_module.__name__)
print(__name__)
$python my_module.py
__main__

$ python main.py
my_module
my_module
__main__

公式ドキュメント

https://docs.python.org/ja/3/reference/import.html?highlight=__name__#name__
https://docs.python.org/ja/3/library/__main__.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?