TIL_18 : Package

JaHyeon Gu·2021년 7월 21일

Python

목록 보기
2/2
post-thumbnail

🙄 패키지


➡ 패키지란?

  • 모듈들을 모아 놓은 디렉토리
  • 일반 디렉토리와 똑같은데 안에 __init__.py 파일이 있다.

shapes 패키지에는 __init__.py 파일과 함께 아래와 같은 모듈이 있다.

shapes/area.py

PI = 3.14

# 원의 넓이
def circle(radius):
	return PI * radius ** 2

# 정사각형 넓이
def square(length):
	return length * length

shapes/volume.py

PI = 3.14

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

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



🙄 패키지 import


➡ import package.module


import shapes.volume

print(shapes.volume.cube(3))

# 27

➡ import package

  • 패키지 자체를 import 할 수도 있지만 패키지 안에 있는 내용들은 import 되지 않음
  • 패키지 안 모듈도 같이 import 하려면 __init__파일을 활용해야 함
  • import ... 방식으로는 모듈의 함수나 변수를 바로 가져올 수 없다
  • import ... 방식으로는 패키지, 모듈만 import 할 수 있다

import shapes

print(shapes.volume.cube(3))

# 오류

➡ from package import module

  • from ... import ... 방식으로 모듈을 바로 가져올 수 있다
  • 모듈 안에 있는 변수나 함수도 가져올 수 있다

from shapes import volume

print(volume.cube(3))

# 27

➡ from package.module import member(s)


from shapes.volume import cube

print(cube(3))

# 27

➡ 이름 변경

  • as 키워드를 써서 이름을 바꿔줄 수 있다.

import shapes.volume as vol

print(vol.cube(3))

# 27



🙄 __init__


➡ __init__ 파일이란?

  • '이 폴더는 파이썬 패키지다'라고 말해주는 파일
  • 패키지나 패키지 안에 있는 어떤 것을 import하면 가장 먼저 init 파일에 있는 코드 실행
  • 3.3 버전 이후 필수가 아니지만 하위 버전과의 호환성과 패키지의 명확성을 위해 항상 만들기 권장

➡ __init__ 파일에서 모듈 import

  • 패키지를 import하면 기본적으로 안에 내용은 import되지 않음
  • 안에 있는 내용도 함께 import하고 싶으면 init파일을 활용해야 함
shapes/__init__.py

from shapes import area, volume
run.py

import shapes

print(shape.area.circle(2))
print(shape.volume.sphere(2))

# 12.56
# 33.4933333333

➡ __init__ 파일에서 함수 import

  • shapes 패키지 안에서 함수들을 직접 가져왔기 때문에 area를 건너뛸 수 있다
  • init파일에서 import되는 것은 항상 package. 으로 접근해야 함
shapes/__init__.py

from shapes.area import circle, square
run.py

import shapes

print(shape.circle(2))
print(shape.square(3))

# 12.56
# 9

➡ __init__ 파일에서 변수 정의하기

  • 여러 모듈에서 쓰이는 상수값은 init파일에 한번만 정의하는 것이 좋다
shapes/__init__.py

PI = 3.14
shapes/area.py

from shapes import PI

def circle(radius):
	...
shapes/volume.py

from shapes import PI

def sphere(radius):
	...
run.py

# PI 직접 import
from shapes import PI

# 패키지 import 후 shapes. 로 접근
import shapes
shapes.PI



🙄 __all__


➡ __all__ 특수 변수

  • import * 를 했을 때 import 대상에서 어떤 것들을 가져와야 하는지 정해 주는 변수
  • 모듈에도 적용되고 패키지에도 적용됨

➡ __all__ & 모듈

  • from shapes.area import * 를 했을 때 모든 내용이 import 되지 않고 circle, square 함수만 import 됨
shapes/area.py

__all__ = ['circle', 'square']

PI = 3.14

# 원의 넓이
def circle(radius):
	return PI * radius ** 2

# 정사각형 넓이
def square(length):
	return length * length

➡ __all__ & 패키지

  • from shapes import * 를 했을 때 area, volume 모듈만 import 됨
shapes.__init__.py

__all__ = ['area', 'volume']



🙄 서브패키지


➡ 서브패키지

  • 패키지 안에 또 다른 패키지가 있을 때 안에 있는 패키지를 서브패키지라고 함
  • shapes, stats는 서브패키지
mymath/
	shapes/
		__init__.py
		area.py
		volume.py
	stats/
		__init__.py
		average.py
		spread.py

➡ 서브패키지 import ...

  • (서브)패키지를 import 할 때는 (서브)패키지 안에서 import 하고 싶은 걸 (서브)패키지의 init 파일에 적어줘야 함
run.py

# 패키지 import
import mymath

# 서브패키지 import
import mymath.shapes

# 모듈 import
import mymath.shapes.area

# 모듈 안에 있는 변수나 함수는 이 방식으로 import 불가능
import mymath.shapes.area.circle 
# 오류

➡ 서브패키지 from... import ...

run.py

# 패키지 안에 있는 패키지 import
from mymath import shapes

# 패키지 안에 있는 모듈 import
from mymath.shapes import area

# 모듈 안에 있는 함수 import
from mymath.shapes.area import circle

# import 뒤에는 . 을 쓸 수 없음
from mymath import shapes.area
# 오류



🙄 상대 경로 import


  • import 하는 곳의 위치를 기준으로 import 하려는 것의 위치를 상대적으로 표현
  • 상대 경로 import 는 항상 . 아니면 .. 으로 시작
  • . 은 현재 패키지 안을 뜻하고 .. 은 상위 패키지 안을 뜻함

➡ init 파일에서 같은 패키지 안에 있는 모듈 가져오기

mymath/shapes/__init__.py

# 절대 경로 임포트
from mymath.shapes import area, volume

# 상대 경로 임포트
from . import area, volume

➡ init 파일에서 같은 패키지 안에 있는 함수 모두 가져오기

mymath/stats/__init__.py

# 절대 경로 임포트
from mymath.stats.average import *
from mymath.stats.spread import *

# 상대 경로 임포트
from .average import *
from .spread import *

➡ 다른 패키지에 있는 함수 가져오기

mymath/shapes/area.py

# 절대 경로 임포트
from mymath.stats.average import data_mean

# 상대 경로 임포트
from ..stats.average import data_mean

위 경우 상대 경로를 봐서는 average 모듈이 정확히 어디 있는지, 패키지 구조가 어떻게 되는지 파악하기가 힘듦, 상대 경로가 복잡해지는 경우에는 그냥 절대 경로를 쓰는 것이 좋다.

profile
IWBAGDS

0개의 댓글