본문 바로가기
Python

[Python] __name__ : Special string variable

by ds31x 2023. 10. 10.

Python에서 module에 할당되는 special attributes 중 하나로서,

해당 module의 이름에 해당하는 문자열로 설정되어 있다.

__name__
Python이 알아서 생성해주는
special string attribute임.

하지만, module이 command line이나 IDE를 통해 직접적으로 main script로 실행되는 경우에는

해당 module의 __name__에는 "__main__" 이라는 문자열이 할당된다.

즉, 다음의 2가지 모드가 존재함.

  • 직접 실행되는 경우 (as main script로) : "__main__"
  • import 문을 통해 간접적으로 실행되는 경우 : 당초 설정된 module의 이름 (일반적으로 import 문에서 사용된 이름)
import math

print(math.__name__)
print(__name__)

다음 파일을 test.py등으로 저장하고, python test.py로 수행하면 다음과 같은 출력을 확인할 수 있음.

mant
__main__

__name__ attribute를 퉁해, 해당 module이 직접 main script로 실행되는지 아니면 import 되어 사용되는지를 구분할 수 있음.

때문에 다음과 같이 main script로 실행될 경우에만 동작하는 부분을 구현할 수 있음.


def my_main():
    """main script일 때 수행되는 함수"""
    print("main script!"

if __name__ == "__main__":
    my_main()

참고로, Python이 자동으로 할당해주는 special attributes로는
__doc__ , __module__ , __annotations__ 등이 있음.

728x90