본문 바로가기
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__" 이라는 문자열이 할당된다.

double underscore __ 로 이름이 시작되고 끝나는 관계로
 
double underscores를 dunder라고도 부름.
Python VM이 설정하는 변수 또는 특별히 사용하는 메서드를 가리킴.

 

변수가 아닌 special method 도 dunder라고 불림:

2023.07.13 - [Python] - [Python] special methods and operator overloading

 

[Python] special methods and operator overloading

Special Methods사용자가 직접 호출하는 경우가 거의 없고, 간접적으로 호출이 됨.즉, 개발자(사용자)가 over-riding을 통해 구현은 하지만 직접 호출하는 경우가 거의 없고,개발자가 다른 built-in function

ds31x.tistory.com

 

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

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

print(math.__name__)
print(__name__)

 

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

math
__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__ 등이 있음.