Python의 패키지 대해 알아봅니다.
game/
__init__.py
sound/
__init__.py
echo.py
wav.py
graphic/
__init__.py
screen.py
render.py
play/
__init__.py
run.py
test.pyC:/doit/game/__init__.py
C:/doit/game/sound/__init__.py
C:/doit/game/sound/echo.py
C:/doit/game/graphic/__init__.py
C:/doit/game/graphic/render.py
# echo.py
def echo_test():
print("echo")
# render.py
def render_test():
print("render")
C:\> set PYTHONPATH=C:/doit
C:\> python
import game.sound.echo
game.sound.echo.echo_test() # echo
from game.sound import echo
echo.echo_test() # echo
from game.sound.echo import echo_test
echo_test() # echo
import game
game.sound.echo.echo_test() # 오류
__init__.py에 정의된 것만 참조할 수 있다.import game.sound.echo.echo_test
# 오류
# C:/doit/game/__init__.py
# game 패키지의 \__init__.py 파일에 공통 변수나 함수를 정의.
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")
import game
print(game.VERSION) # 3.5
game.print_version_info() # The version of this game is 3.5.
# C:/doit/game/__init__.py
# 패키지 내의 다른 모듈을 미리 import
from .graphic.render import render_test
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")
# 패키지를 사용하는 코드에서는 간편하게 game 패키지를 통해 render_test 함수를 사용할 수 있다.
import game
game.render_test() # render
# C:/doit/game/__init__.py
from .graphic.render import render_test
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")
# 여기에 패키지 초기화 코드를 작성한다.
print("Initializing game ...")
# 패키지를 처음 import할 때 초기화 코드가 실행된다.
import game
# Initializing game ...
# game 패키지의 초기화 코드는 game 패키지의 하위 모듈의 함수를 import할 경우에도 실행된다.
from game.graphic.render import render_test
# Initializing game ...
# game 패키지를 import한 후에 하위 모듈을 다시 import 하더라도 초기화 코드는 처음 한 번만 실행된다.
import game
# Initializing game ...
from game.graphic.render import render_test
# 초기화 코드 실행 안됨
from game.sound import *
# Initializing game ...
echo.echo_test() # echo라는 이름이 정의되지 않았다는 오류 발생.
__all__ 변수를 설정하고 import할 수 있는 모듈을 정의해 주어야 한다.# C:/doit/game/sound/__init__.py
__all__ = ['echo']
# sound 디렉터리에서 *를 사용하여 import할 경우, 이곳에 정의된 echo 모듈만 import된다는 의미.
from game.sound import *
# Initializing game ...
echo.echo_test() #echo
from game.sound.echo import *은 __all__과 상관없이 import된다. 이렇게 __all__과 상관없이 무조건 import되는 경우는 from a.b.c import *에서 from의 마지막 항목인 c가 모듈인 때이다.# render.py
from game.sound.echo import echo_test # 전체 경로를 사용하여 import
from ..sound.echo import echo_test # 상대경로로 import하는 것도 가능
def render_test():
print("render")
echo_test()
from game.graphic.render import render_test
# Initializing game ...
render_test()
# render
# echo