[파이썬]

[파이썬] 모듈과 패키지

뽕규의 스케치북 2025. 2. 12. 14:10
728x90

모듈 만들기

모듈을 만드는 법은 간단하다

단순히 파일을 만들고 외부에서 읽어오면 된다

모듈을 구조화해서 큰 모듈(패키지)를 만드는 기능도 제공한다

모듈 만들기

#module_basic/test_module.py

PI = 3.141592

def number_input():
    output=input("input digit>: ")
    return float(output)

def get_circumference(radius):
    return 2*PI*radius

def get_circle_area(radius):
    return PI*radius**2
#module_basic/main.py

import test_module as test

radius = test.number_input()
print(test.get_circumference(radius))
print(test.get_circle_area(radius))

name == “main

이것의 의미를 알아보자

name

파이썬 코드 내부에선__name__이라는 변수를 사용할 수 있다

>>> __name__
'__main__'

프로그래밍 언어에선 프로그램의 시작점을 엔트리 포인트 또는 메인이라고 부른다

이런 엔트리포인트 혹은 메인 내부에서의 name 값은 ‘main’ 이다

모듈의 name

모듈 내부에서 __name__을 출력하고 비교하기

#main.py
import test_module
print(__name__)
#test_module.py
print(__name__)
#main.py에서 실행했을때 result
test_module
__main__

엔트리 포인트에선 __main__을 출려가지만 엔트리 포인트 파일 내에서 import 된 모듈은 모듈 내 코드가 실행되며 모듈의 이름을 출력하는 것을 볼 수 있다

name 활용하기

엔트리포인트에선 ‘main’이라는 값을 반환하기 때문에 이를 활용하여 현재 파일이 모듈로 실행되는지 엔트리 포인트로 실행되는지 알 수 있다

#main.py

import test_module as test

radius = test.number_input()
print(test.get_circumference(radius))
print(test.get_circle_area(radius))
#test_module.py

PI = 3.141592

def number_input():
    output=input("input digit>: ")
    return float(output)

def get_circumference(radius):
    return 2*PI*radius

def get_circle_area(radius):
    return PI*radius**2

if __name__ == '__main__':
    print('get_circumference(10):', get_circumference(10))
    print('get_circle_area(10):', get_circle_area(10))

test_module.py에 if 문이 없었다면 main.py를 실행했을 때 test_module에 있는 프린트 문이 실행되고 main에 코드가 실행되야하지만 if문으로 __name__이 ‘main’일때, 즉, 엔트리 포인트가 test_module일때만 프린트를 하라고 조건을 걸어놨기 때문에 test_module의 프린트문은 main을 실행했을땐 실행되지 않는다

패키지

  • pip → Python Package Index의 줄임말로 패키지 관리 시스템이다
  • 모듈이 모인것 → 패키지

패키지 만들기

variable_a = "a module variable"
variable_b = "b module variable"
import test_package.module_a as a
import test_package.module_b as b

print(a.variable_a)
print(b.variable_b)

#result
a module variable
b module variable

init.py 파일

패키지를 읽을 때 어떤 처리를 해야되거나 패키지 내부 모듈들을 한꺼번에 가져오고 싶을때 init.py를 패키지 내부에 만들어 사용한다

init.py는 해당 폴더가 패키지이을 알려주고, 피키지와 관련된 초기화를 처리하는 파일이다

init.py에 __all__이라는 리스트를 만드는데 이 리스트에 지정한 모듈이 [from 패키지이름 import *]을 할 때 전부 읽어 들여진다

#from test_package import *로 모듈을 읽어 들일 때 가져올 모듈
__all__ = ["module_a", "module_b"]

#패키지를 읽어 들일 때 처리를 작성할 수도 있음
print("test_package를 읽었다")
from test_package import *

print(module_a.variable_a)
print(module_b.variable_b)

 

728x90