ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] __all__ 의 역할
    Programming/Python 2022. 8. 9. 16:42

    __all__ 변수의 역할

    어떤 라이브러리 내의 패키지를 분석할 때 보통 __init__.py 를 살펴보게 된다.

    이때, __all__ 이라는 변수에 다른 패키지에 속한 함수나 클래스의 이름들을 리스트로 만들어 할당하는 것을 볼 수 있다.

    이 변수의 역할은 다른 파일에서 특정 패키지를 `from lib import *`와 같이 쓸 때, *에 들어갈 변수, 함수, 클래스들을 선언하는 것이다.

     

    +-- folder
    |    +-- all.py
    |    +-- points.py

    # ex) points.py
    __all__ = ['Points', 'add']
    
    class Points:
        pt1 = (1, 2)
        pt2 = (-1, -2)
    
    def add(pt1, pt2):
        x = pt1[0] + pt2[0]
        y = pt2[1] + pt2[1]
        return (x, y)
    
    def sub(pt1, pt2):
        x = pt1[0] - pt2[0]
        y = pt2[1] - pt2[1]
        return (x, y)
    # ex) all.py
    from points import *
    
    pts = Points()
    print(add(pts.pt1, pts.pt2)) # (0, 0)
    print(sub(pts.pt1, pts.pt2)) # Error: name 'sub' is not defined

    points.py에서 __all__ 변수에 sub를 넣지 않았기 때문에 에러가 발생한다.

    댓글

Designed by Tistory.