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?

モジュールの__name__と__main__について

Last updated at Posted at 2025-03-04

Pytonモジュールを勉強していく途中、__name__と__main__の内容が出てきたので、ここに書き留めておく。

import文の処理

通常import文を使うときは、スクリプトの先頭に記述していくが、importされる側の処理が、例えばプリントのみの場合、import文で呼びだした側のスクリプトには、importされた時点で、print関数が読み込まれ、意図せずに出力されてしまう場合がある。

lesson.py
import lesson_packege.talk.animal

import config

animal.py
def sing ():
    return "#kjaflds;jfiewanfkla;nisesing"

print(sing())
config.py
print("config:",__name__)
lesson.py 出力
#kjaflds;jfiewanfkla;nisesing
config: config

プロジェクト内で、インポート先のスクリプトにテスト用として出力されるものがあった場合、インポートした際に、意図せず出力されてしまう。

問題の解決策

この問題を解消するために、if文を使いスクリプトを作成する。

animal.py
def sing ():
    return "#kjaflds;jfiewanfkla;nisesing"

if __name__ == "__main__":
   print(sing())
   print("animal:",__name__)

lesson.py
import lesson_packege.talk.animal

import config 

出力
config: config

animal.pyのように、もしスクリプトがmainであるならばsing()を出力せよ。と記述すれば、lesson.pyを実行する時に、animal.pyはmainではないので、出力されなくなる。
※__name__はスクリプト名として処理をされるが、実行するスクリプトは__main__として処理される。

具体例

lesson.py
import lesson_packege.talk.animal

import config #importされた時点で、実行されるプリントがあったら実行されてしまう。

def main() : #このスクリプトもインポートされる可能性があるため、関数に閉じておく
   lesson_packege.talk.animal.sing()

if __name__ == "__main__": #このスクリプトがインポートされた時に勝手に出力されない用
    main()

print("lesson",__name__)

animal.py

def sing ():
    return "#kjaflds;jfiewanfkla;nisesing"


if __name__ == "__main__":
   print(sing())
   print("animal:",__name__)

config.py
print("config:",__name__)
lesson.py出力
config: config
lesson __main__

実際のアプリケーション開発では、このように記述する

0
0
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
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?