Python

[Python] __init__.py

비번변경 2023. 2. 10. 17:19

__init__.py

Python에서 하나의 Python 파일(*. py)을 모듈(Module)이라고 한다. 그리고 모듈의 집합을 패키지(Package)라고 한다.

__init__.py 파일은 디렉터리가 파이썬 패키지의 일부임을 알려주는 역할을 하는데, 여러 Python 모듈을 import 하는 메커니즘을 제공한다.

Python 3.3 이후부터는 필수적인 파일이 아니게 되었으나 하위 버전 간의 호환성과 패키지의 명확성을 위해 생성하는 것을 권장한다.

 

이 글에서는 __init__.py 작성 방법을 정리해둔다. (Python 3.3 미만에서는 정상적으로 동작하지 않을 수 있다.)

 

 

예제

예시로 사용할 Package의 구조와 내용은 아래와 같다.

./shape/area.py

PI = 3.14

# 원의 면적
def circle(radius):
    return PI * radius ** 2

# 정사각형의 면적
def square(length):
    return length ** 2

 

./shape/volume.py

PI = 3.14

# 구의 부피
def sphere(radius):
    return (4 / 3) * PI * radius ** 3

# 정육면체의 부피
def cube(length):
    return length ** 3

 

 

__init__.py 생성 및 작성

shape 디렉터리에 __init__.py를 생성한다. __init__.py가 존재하면 해당 디렉터리는 패키지로 인식되기 때문에 내용은 없어도 된다.

__init__.py에 의해 shape 패키지가 정상적으로 인식된다면 패키지 밖의 main.py에서 아래와 같은 코드로 모듈을 import하여 사용할 수 있다.

import shape
from shape import area
from shape import volume

print(shape.area.square(4))
print(area.square(4))

print(shape.volume.cube(4))
print(volume.cube(4))

 

만약 정상적으로 인식하지 않으면 __init__.py 내 아래와 같이 import할 모듈을 정의한다.

from shape import area
from shape import volume

 

__init__.py 내 변수 작성

패키지 내에서 공용으로 사용하는 변수는 패키지 수준에서 정의한 후 각 모듈에서 import 하여 사용할 수 있다.

 

./shape/__init__.py

PI = 3.14

from shape import area, volume

 

../shape/area.py

from shape import PI

def circle(radius):
    return PI * radius ** 2
...

 

 

./shape/volume.py

from shape import PI

def sphere(radius):
    return (4 / 3) * PI * radius ** 3
...

 

 

특수 변수 __all__

from <package> import * 구문에서 import 할 모듈을 정의한다.

 

./shape/__init__.py

PI = 3.14

from shape import area, volume

__all__ = ['area', 'volume']

이제 아래와 같은 코드로 shape 패키지 내 모듈을 import 할 수 있다.

from shape import *

print(area.square(4))
print(volume.cube(4))

 

 

 

참고 문서

https://dojang.io/mod/page/view.php?id=2449 

https://chancoding.tistory.com/207

https://mmjourney.tistory.com/14

https://wikidocs.net/1418

728x90