Original article: Python if __name__ == __main__ Explained with Code Examples

파이썬 인터프리터(interpreter)가 파이썬 파일을 읽을 때 몇 가지 특별 변수를 먼저 설정합니다. 그리고나서 파일의 코드를 실행합니다.

특별 변수 중 하나는 __name__이라고 합니다.

이 글을 순서대로 따라서 코드 문단을 읽어본다면 if __name__ == "__main__"를 어떻게 사용하고 이것이 왜 중요한지 배우게 될 것입니다.

파이썬 모듈 설명

파이썬 파일은 모듈을 호출하는데 .py 파일 확장자에 의해 식별됩니다. 하나의 모듈은 함수와 클래스, 변수를 정의할 수 있습니다.

그래서 인터프리터가 모듈을 메인 프로그램에서 실행한다면 __name__ 변수는 __main__으로 설정될 것입니다.

하지만 코드가 다른 모듈로부터 모듈을 불러오고 있다면 __name__ 변수는 그 모듈의 이름대로 설정될 것입니다.

예제를 살펴봅시다. file_one.py라는 이름으로 파이썬 모듈을 생성하고 그 안에 아래 코드를 붙여넣으세요:

# Python file one module

print("File one __name__ is set to: {}" .format(__name__))
file_one.py

이 파일을 실행하면 우리가 이야기하던 것이 무엇인지 정확히 보게 될 것입니다. 이 모듈의 변수 __name____main__으로 설정됩니다:

File one __name__ is set to: __main__

이제 file_two.py라는 이름으로 다른 파일을 더하고 그 안에 아래 코드를 붙여넣으세요:

# Python module to import

print("File two __name__ is set to: {}" .format(__name__))
file_two.py

또한 file_one.py 안의 코드를 아래와 같이 수정하여 우리가 file_two.py 모듈을 불러올 수 있도록 하세요:

# Python module to execute
import file_two

print("File one __name__ is set to: {}" .format(__name__))
file_one.py

file_one 코드를 다시 실행하면 file_one안에 있던 __name__ 변수가 바뀌지 않고 여전히 __main__으로 설정되어 남아있는 것을 보여줄 것입니다. 그러나 이제 file_two안에 있던 __name__ 변수가 모듈 이름, 즉 file_two로 설정되었습니다.

결과는 아래와 같아 보여야 합니다:

File two __name__ is set to: file_two
File one __name__ is set to: __main__

하지만 file_two를 직접 실행하면 그 이름이 __main__으로 설정된 것을 보게 될 것입니다:

File two __name__ is set to: __main__

실행하는 파일/모듈을 위한 변수 __name__은 항상 __main__으로 될 것입니다. 그러나 모든 다른 모듈에서 불러들여지는 __name__ 변수는 그 자신의 모듈 이름으로 설정될 것입니다.

파이썬 파일 이름을 정하는 관습

일반적으로 __name____main__을 사용하는 방법은 아래와 같이 보입니다:

if __name__ == "__main__":
   Do something here

이것이 실제로 동작하는 법을 보고 해당 변수들을 실제로 어떻게 사용할지 봅시다.

file_onefile_two를 아래와 같이 수정하세요:

file_one:

# Python module to execute
import file_two

print("File one __name__ is set to: {}" .format(__name__))

if __name__ == "__main__":
   print("File one executed when ran directly")
else:
   print("File one executed when imported")
file_one.py

file_two:

# Python module to import

print("File two __name__ is set to: {}" .format(__name__))

if __name__ == "__main__":
   print("File two executed when ran directly")
else:
   print("File two executed when imported")
file_two.py

다시 file_one을 실행하면 프로그램이 두개의 모듈 중 어느 것이 __main__인지 인식하고 우리의 첫번째 if else문에 따라 코드를 실행하는 것을 보게 될 것입니다.

결과는 아래와 같아 보여야 합니다:

File two __name__ is set to: file_two
File two executed when imported
File one __name__ is set to: __main__
File one executed when ran directly

이제 file_two를 실행하여 __name__변수가 __main__으로 설정된 것을 보게 될 것입니다:

File two __name__ is set to: __main__
File two executed when ran directly

이와 같은 모듈을 불러와서 실행할 때는 그 안의 함수들을 불러오게 되고 최상단 코드가 실행될 것입니다.

이 과정이 실행되는 것을 보기 위해, 파일을 아래와 같이 수정하세요:

file_one:

# Python module to execute
import file_two

print("File one __name__ is set to: {}" .format(__name__))

def function_one():
   print("Function one is executed")

def function_two():
   print("Function two is executed")

if __name__ == "__main__":
   print("File one executed when ran directly")
else:
   print("File one executed when imported")
file_one.py

file_two:

# Python module to import

print("File two __name__ is set to: {}" .format(__name__))

def function_three():
   print("Function three is executed")

if __name__ == "__main__":
   print("File two executed when ran directly")
else:
   print("File two executed when imported")
file_two.py

이제 함수들이 읽혀졌을 테지만 실행되진 않았습니다.

이들 함수들 중 하나를 실행하기 위해서 file_oneif __name__ == "__main__" 부분을 아래와 같이 보이게 수정하세요:

if __name__ == "__main__":
   print("File one executed when ran directly")
   function_two()
else:
   print("File one executed when imported")

file_one을 실행하면 아래와 같은 것을 보게 될 것입니다:

File two __name__ is set to: file_two
File two executed when imported
File one __name__ is set to: __main__
File one executed when ran directly
Function two is executed

또한 불러온 파일에서 함수를 실행할 수도 있습니다. 이를 위해서 file_oneif __name__ == "__main__" 부분을 아래와 같이 보이게 수정하세요:

if __name__ == "__main__":
   print("File one executed when ran directly")
   function_two()
   file_two.function_three()
else:
   print("File one executed when imported")

그러면 아래와 같은 결과를 기대할 수 있습니다:

File two __name__ is set to: file_two
File two executed when imported
File one __name__ is set to: __main__
File one executed when ran directly
Function two is executed
Function three is executed

(우리는 2개를 사용하고 있지만) 만약 file_two 모듈이 정말 많은 함수들을 가지고 있어 파일이 크고 우리가 그 모든 것들을 불러오고 싶지는 않다고 해 봅니다. file_two를 아래와 같이 보이게 수정하세요:

# Python module to import

print("File two __name__ is set to: {}" .format(__name__))

def function_three():
   print("Function three is executed")

def function_four():
   print("Function four is executed")

if __name__ == "__main__":
   print("File two executed when ran directly")
else:
   print("File two executed when imported")
file_two.py

그리고 해당 모듈에서 특정한 함수를 불러오기 위해서 file_one 안에 from 불러오기(import) 단락을 사용하세요:

# Python module to execute
from file_two import function_three

print("File one __name__ is set to: {}" .format(__name__))

def function_one():
   print("Function one is executed")

def function_two():
   print("Function two is executed")

if __name__ == "__main__":
   print("File one executed when ran directly")
   function_two()
   function_three()
else:
   print("File one executed when imported")
file_one.py

결론

어떤 파일을 메인 프로그램으로 실행할 수 있는지 또는 다른 모듈에 의해 불러오게 할 것인지에 따라 __name__ 변수를 위한 정말 좋은 활용 사례가 있습니다. 우리는 모듈들을 불러올 때 코드 일부분들을 실행하게 허용하거나 막기 위해서 if __name__ == "__main__"을 사용할 수 있습니다.

파이썬 인터프리터가 파일을 읽을 때 __name__ 변수는 해당 모듈이 실행된다면 __main__으로 설정되고 해당 모듈을 불러오는 것이라면 모듈의 이름으로 설정됩니다. 파일을 읽으면 모든 상위 레벨 코드를 실행되지만 함수와 클래스들은 (불러와지기만 할 뿐이라) 실행되지 않습니다.

Bra gjort! (스웨덴어로 "아주 잘했다"를 의미합니다!)

이와 같은 글이 저의 freeCodeCamp 프로필Medium 프로필에 더 많이 있고 깃허브(GitHub) 페이지에는 만들어둔 다른 재미있는 것들이 있으니 확인해 보세요.