티스토리 뷰

파이썬 파일을 import 해서 원하는 함수만을 사용하려고 할 때, 

if __name__ == "__main__": 내에 있는 스크립트는 import시 제외된다.

 

예시를 보자.

# forModule.py

def forPrint():
	return "hello!"

print(forPrint())	#hello! 출력됨
#useModule.py

import forModule	#벌써 여기서 hello! 출력됨

print forModule.forPrint()	#hello! 출력됨

하지만 우리가 원하는건 오직 forModule의 forPrint 함수만 사용하기 위함이다. return 까지만!

그렇기 때문에, 아래와 같이 수정해준다.

# forModule.py

def forPrint():
	return "hello!"
if __name__ == "__main__":
	print(forPrint())	#hello! 출력됨
#useModule.py

import forModule	#forPrint 함수만 가지고 있다.

print forModule.forPrint()	#hello! 출력됨

그래서 모듈을 인터프리터에서 직접 사용하는 경우에만 if문 내의 코드를 실행하라는 의미라고 한 이유가 이것이었다.

직접 사용하지 않고 useModule.py처럼 import해서 사용하는 경우는 forModule의 if문이 실행되지 않는다.

우리가 원하는건 오직 함수이기 때문이다.

 


참고:

medium.com/@chullino/if-name-main-%EC%9D%80-%EC%99%9C-%ED%95%84%EC%9A%94%ED%95%A0%EA%B9%8C-bc48cba7f720

bestpractice80.tistory.com/30

반응형
댓글