# ๐ค How Import Statement Finds Modules & Packages - 2

Min-Ho Leeยท2020๋ 6์ 30์ผ
0

๋ชฉ๋ก ๋ณด๊ธฐ
16/22

Tuesday_June_30
.
.
.

# 4๏ธโฃ Calculator ํจํค์ง ๋ง๋ค๊ธฐ

์์ ๊ฐ์ ๊ตฌ์กฐ๋ก ๋ง๋ค์ด์ผ ํ๋ค.

test_python ์ด๋ผ๋ ์ต์์ ํด๋ ์์ calculator๋ผ๋ ๋๋ ํฐ๋ฆฌ์ main.py ํจ์๋ฅผ ๋ง๋ค์๊ณ
calculator ๋ผ๋ ๋๋ ํฐ๋ฆฌ์๋ (์ธ๋๋ฐ์ธ๋๋ฐ)ini(์ธ๋๋ฐ์ธ๋๋ฐ).py, add_and_multiply.py, multiplication.py ๋ฅผ ๋ง๋ค์ด ์ฃผ์๋ค.

๊ฐ ํ์ผ์ ๋ด์ฉ์ ๋ค์๊ณผ ๊ฐ๋ค.

(์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ >> ๋ด์ฉ์ ์๋ค.

from .multiplication import multiply
# from calculator.multiplication import multiply
return multiply(a,b) + (a+b)

## multiplication.py

def multiply(a,b):
return(a*b)

## main.py

# absoulte path

# relative path

if __name__ == '__main__':
print(add_and_multiply(1,2))

# 5๏ธโฃ main.py์์ import ๊ฒฝ๋ก์ ๋ฐ๋ฅธ ์๋ฌ

main ํ์ผ์์ ์ ๋๊ฒฝ๋ก๋ก add_and_multiply๋ฅผ import ํด์ฃผ์๋ค.

๊ทธ๋ฐ๋ฐ ๋ง์ฝ ์๋๊ฒฝ๋ก์ธ
๋ก import๋ฅผ ํ๊ฒ ๋๋ฉด,

# absoulte path

# relative path

if __name__ == '__main__':
print(add_and_multiply(1,2))

๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.

ImportError: attempted relative import with no known parent package

ํ์ด์ฌ์ ์คํํ๋(main)ํ์ผ์ ๋ฌด์กฐ๊ฑด x 100 ์ ๋ ๊ฒฝ๋ก๋ก ๋ชจ๋์ด๋ ํจํค์ง๋ฅผ ๊ฐ์ ธ์์ผ ํ๋ค๊ณ  ํ๋ค.
๊ณต์๋ฌธ์์ ๊ทธ๋ ๊ฒ ๋์์๋ค. ์ดํดํ๋ ค๋ค ๋จธ๋ฆฌ๊ฐ ํฐ์ง๋ปํ๋ค.

์ฌ๊ธฐ์ ์ค์ํ ๊ฒ์, ์ด๋ฆ์ด main์ธ ํจ์์์ ์ ๋ ๊ฒฝ๋ก๋ก import๋ฅผ ํ๋ ๊ฒ์ด ์๋๋ผ,
์คํ์ค์ธ ํ์ผ์ main ํ์ผ์ด๋ผ๊ณ  ํ๋ ๊ฒ์ด๋ค.

# 6๏ธโฃ add_and_multiply.py์์ multiple ํจ์๋ฅผ ๊ฒฝ๋ก ๋ณ๋ก importํ๊ณ  main ๋ชจ๋๊ณผ์ ์ฐจ์ด์  ์์๋ณด๊ธฐ

add_and_multiply.py ํ์ผ์ ์คํ์ค์ธ ํ์ผ(main)์ด ์๋๊ธฐ ๋๋ฌธ์, ์ด๋ ํ ๊ฒฝ๋ก๋ก muriplication ๋ชจ๋์ multiple ํจ์๋ฅผ ๊ฐ์ ธ์๋ ์๊ด์ด ์๋ค.
์๋ฌ ๋ํ ๋์ง ์๋๋ค.

์ฐจ์ด์ ์ด๋ผ๊ธฐ ๋ณด๋จ, import์ ์ ๋ ๊ฒฝ๋ก์ ์๋ ๊ฒฝ๋ก ๋ชจ๋ ๊ฐ๋ฅํ์ง๋ง, ์คํํ๋ ํ์ผ(main)์์๋ ์ ๋ ๊ฒฝ๋ก๋ก๋ง import๋ฅผ ํด์ฃผ๋ฉด ๋๋ค.

# 7๏ธโฃ (์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ?

(์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ์ ํด๋น ๋๋ ํฐ๋ฆฌ๊ฐ ํจํค์ง์ ์ผ๋ถ๋ผ๋ ๊ฒ์ ์๋ ค์ฃผ๋ ์ญํ ์ ํ๋ค. ๋ง์ฝ calculatorํจํค์ง์ (์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ์ด ์๋ค๋ฉด, calculator๋ผ๋ ํจํค์ง๋ฅผ ํจํค์ง๋ผ๊ณ  ์ธ์์ ๋ชปํ๊ฒ ๋๋ค.

**๊ทธ๋ฐ๋ฐ python3.3 ๋ฒ์ ๋ถํฐ๋ (์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ์ด ์์ด๋ ํจํค์ง๋ก ์ธ์ ํ์ง๋ง(PEP 420) ํ์ ๋ฒ์  ํธํ์ ์ํด (์ธ๋๋ฐ์ธ๋๋ฐ)init(์ธ๋๋ฐ์ธ๋๋ฐ).py ํ์ผ์ ์์ฑํ๋ ๊ฒ์ด ์์ ํ ๋ฐฉ๋ฒ์ด๋ผ๊ณ  ํ๋ค.

๐ Rabbit can take a rest, but ๐ข turtle can't