__init__.py

Published by onesixx on

https://okimaru.tistory.com/169

__init__.py

  • 폴더가 패키지로 인식되도록 하는 역할
  • 패키지를 초기화하는 역할
  • import 패키지명 은  init.py 파일이 실행되므로,
    init.py에서 (from . import 모듈 형식으로) 현재 패키지에서 모듈을 가져오게 만들어야 한다.
  • python3.3 버전부터는 init.py 파일이 없어도 패키지로 인식(PEP 420) 하지만
    하위 버전 호환을 위해 init.py 파일을 생성하는 것이 안전한 방법이다.

패키지 = 모듈의 집합

모듈 = python 파일

init사용 비교

#stringLength.py
def stringLength(inStr):
    return len(inStr)
#stringToUpper.py
def stringToUpper(inStr):
    return inStr.upper()
#stringToLower.py
def stringToLower(inStr):
    return inStr.lower()

pythonProject

l__stringLength.py

l__stringToLower.py

l__stringToUpper.py

l__ example1.py








#example1.py
import stringToLower
import stringToUpper
import stringLength

test_string = "Hello, World!"

print(stringLength.stringLength(test_string))
print(stringToUpper.stringToUpper(test_string))
print(stringToLower.stringToLower(test_string))

pythonProject

l__myStrPackage

    l__ __init__.py

    l__ stringLength.py

    l__ stringToLower.py

    l__ stringToUpper.py

l__ example2.py

#__init__.py
from .stringLength  import stringLength
from .stringToUpper import stringToUpper
from .stringToLower import stringToLower
#example2.py
import myStrPackage



test_str = "Hello, World"

print(myStrPackage.stringLength(test_str))
print(myStrPackage.stringToLower(test_str))
print(myStrPackage.stringToUpper(test_str))

패키지 파일을 사용하니 엄청 깔끔해졌다.

__init__.py 패키지 파일에서 from 이름 앞에 . 을 붙이는 이유는 파이썬 3버전에서 relative import 가 가능해지도록 변경됐다.

__all__

  • 특정 디렉터리의 모듈을 *를 이용하여 import할 때에는 다음과 같이 해당 디렉터리의 init.py 파일에 all이라는 변수를 설정하고 import할 수 있는 모듈을 정의해 주어야 한다. all로 정의하지 않으면 인식되지 않는다.
# __init__.py
__all__ = ['echo']
  • 여기에서 all이 의미하는 것은 sound 디렉터리에서 * 기호를 사용하여 import할 경우 이곳에 정의된 echo 모듈만 import된다는 의미이다.

Categories: dash

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x