KR_Module - somaz94/python-study GitHub Wiki
λͺ¨λμ νμ΄μ¬ μ½λλ₯Ό λ Όλ¦¬μ μΌλ‘ λ¬Άμ΄λμ λ¨μλ‘, μ¬μ¬μ© κ°λ₯ν μ½λλ₯Ό νμΌ λ¨μλ‘ κ΄λ¦¬ν μ μκ² ν΄μ€λ€.
# mymath.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
β λͺ¨λμ μ£Όμ νΉμ§:
- μ½λ μ¬μ¬μ©μ±: νλ² μμ±ν μ½λλ₯Ό μ¬λ¬ νλ‘κ·Έλ¨μμ νμ©
- λ€μμ€νμ΄μ€ κ΄λ¦¬: μ΄λ¦ μΆ©λ λ°©μ§ λ° μ½λ ꡬ쑰ν
- κΈ°λ₯ λΆλ¦¬: κ΄λ ¨ κΈ°λ₯μ λ Όλ¦¬μ μΌλ‘ κ·Έλ£Ήν
- μ μ§λ³΄μ μ©μ΄: κ΄λ ¨ μ½λλ₯Ό λ 립μ μΌλ‘ κ΄λ¦¬
# μ 체 λͺ¨λ μν¬νΈ
import mymath
# νΉμ ν¨μ/λ³μλ§ μν¬νΈ
from mymath import add, PI
# λͺ¨λ μμ μν¬νΈ (κΆμ₯νμ§ μμ)
from mymath import *
# λ³μΉ μ¬μ©
import mymath as mm
β μν¬νΈ λ°©μλ³ νΉμ§:
-
import λͺ¨λλͺ
: λͺ¨λ λ€μμ€νμ΄μ€λ₯Ό μ μ§νλ©° μ κ·Ό (μ:λͺ¨λλͺ .ν¨μ()
) -
from λͺ¨λ import μ΄λ¦
: νΉμ μ΄λ¦λ§ νμ¬ λ€μμ€νμ΄μ€λ‘ κ°μ Έμ΄ -
import λͺ¨λ as λ³μΉ
: λͺ¨λλͺ μ λ μ§§κ±°λ λͺ νν μ΄λ¦μΌλ‘ μ¬μ© -
from λͺ¨λ import *
: λͺ¨λ κ³΅κ° μ΄λ¦μ κ°μ Έμ€μ§λ§ λ€μμ€νμ΄μ€ μ€μΌ μν
# test_module.py
def main_function():
print("λ©μΈ κΈ°λ₯ μ€ν")
if __name__ == "__main__":
# μ΄ νμΌμ΄ μ§μ μ€νλ λλ§ μ€νλ¨
main_function()
β μ£Όμ μ©λ:
- λͺ¨λ ν μ€νΈ: λͺ¨λ μ체 μ€ν μ ν μ€νΈ μ½λ μ€ν
- λΌμ΄λΈλ¬λ¦¬/μ ν리μΌμ΄μ μ΄μ€ μ©λ: κ°μ μ½λλ₯Ό λΌμ΄λΈλ¬λ¦¬μ μ€ν¬λ¦½νΈλ‘ νμ©
- μ€ν¬λ¦½νΈ μ§μ μ : λͺ¨λ μ§μ μ€ν μ μμμ μ§μ
- λͺ¨λ μν¬νΈ μ λΆνμν μ½λ μ€ν λ°©μ§
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
β ν¨ν€μ§ νΉμ§:
- λͺ¨λμ κ³μΈ΅μ ꡬ쑰ν: κ΄λ ¨ λͺ¨λμ λλ ν λ¦¬λ‘ κ΅¬μ‘°ν
-
__init__.py
: λλ ν 리λ₯Ό ν¨ν€μ§λ‘ μΈμνκ² νλ νμΌ (Python 3.3+ μμλ μ νμ¬ν) - νμ ν¨ν€μ§: 무μ ν μ€μ²© κ°λ₯ν κ³μΈ΅ ꡬ쑰
- λ€μμ€νμ΄μ€ ν¨ν€μ§: Python 3.3+ μμλ
__init__.py
μμ΄λ κ°λ₯
import sys
# νμ¬ λͺ¨λ κ²μ κ²½λ‘ νμΈ
print(sys.path)
# κ²μ κ²½λ‘ μΆκ°
sys.path.append('/path/to/my/modules')
β κ²μ κ²½λ‘ μ°μ μμ:
- νμ¬ μ€ν μ€μΈ μ€ν¬λ¦½νΈμ λλ ν 리
-
PYTHONPATH
νκ²½ λ³μμ μ§μ λ λλ ν 리 - Python μ€μΉ μ κΈ°λ³Έ λΌμ΄λΈλ¬λ¦¬ κ²½λ‘
- μ¬μ΄νΈ ν¨ν€μ§ (pip λ±μΌλ‘ μ€μΉν ν¨ν€μ§)
-
.pth
νμΌμ μ§μ λ κ²½λ‘
import importlib
# λͺ¨λ μ¬λ‘λ©
importlib.reload(my_module)
β μ¬λ‘λ© μ¬μ© μλ리μ€:
- κ°λ° μ€ λͺ¨λ μμ μ λ³κ²½μ¬ν μ μ©
- μ₯μκ° μ€ν μ ν리μΌμ΄μ μμ λͺ¨λ λμ μ λ°μ΄νΈ
- λͺ¨λ μν μ΄κΈ°ν
- λλ²κΉ λ° ν μ€νΈ
νμ΄μ¬μ λ€μν κΈ°λ₯μ μ 곡νλ νμ€ λΌμ΄λΈλ¬λ¦¬ λͺ¨λμ ν¬ν¨νλ€.
# νμΌ μμ€ν
μμ
import os
print(os.getcwd()) # νμ¬ μμ
λλ ν 리 μΆλ ₯
# κ²½λ‘ μ‘°μ
import os.path
print(os.path.join('folder', 'file.txt')) # 'folder/file.txt' (Unix) λλ 'folder\\file.txt' (Windows)
# μ κ· ννμ
import re
result = re.search(r'\d+', 'abc123def')
print(result.group()) # '123'
# μκ° κ΄λ ¨ κΈ°λ₯
import time
print(time.time()) # μ λμ€ νμμ€ν¬ν μΆλ ₯
# λ μ§ λ° μκ° μ²λ¦¬
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d")) # μ€λ λ μ§ μΆλ ₯
# JSON μ²λ¦¬
import json
data = json.dumps({'name': 'John', 'age': 30})
print(data) # '{"name": "John", "age": 30}'
# λμ μμ±
import random
print(random.randint(1, 10)) # 1λΆν° 10 μ¬μ΄μ λμ μΆλ ₯
β μμ£Ό μ¬μ©λλ λ΄μ₯ λͺ¨λ:
-
os
,sys
: μ΄μ체μ μΈν°νμ΄μ€, μμ€ν κ΄λ ¨ κΈ°λ₯ -
datetime
,time
: λ μ§ λ° μκ° μ²λ¦¬ -
math
,random
: μν ν¨μ, λμ μμ± -
json
,csv
,xml
: λ°μ΄ν° νμ μ²λ¦¬ -
re
: μ κ· ννμ -
collections
: νΉμ 컨ν μ΄λ μλ£ν -
itertools
,functools
: λ°λ³΅ λ° ν¨μν λꡬ -
urllib
,http
: λ€νΈμν¬ λ° μΉ κ΄λ ¨ κΈ°λ₯
# module_a.py
var = "λͺ¨λ Aμ λ³μ"
# module_b.py
var = "λͺ¨λ Bμ λ³μ"
# main.py
import module_a
import module_b
print(module_a.var) # "λͺ¨λ Aμ λ³μ"
print(module_b.var) # "λͺ¨λ Bμ λ³μ"
var = "λ©μΈμ λ³μ"
print(var) # "λ©μΈμ λ³μ"
β λ€μμ€νμ΄μ€ κ΄λ¦¬:
- λͺ¨λ λ€μμ€νμ΄μ€: κ° λͺ¨λμ λ 립μ μΈ μ΄λ¦ κ³΅κ° μ 곡
- μ΄λ¦ μΆ©λ λ°©μ§: λμΌν μ΄λ¦μ κ°μ²΄λ λͺ¨λλ³λ‘ ꡬλΆ
- μ¬λ³Ό κ°μμ±:
_
λ‘ μμνλ μ΄λ¦μ λΉκ³΅κ° μ¬λ³Όλ‘ κ°μ£Ό - κΈλ‘λ² λ€μμ€νμ΄μ€: λ©μΈ νλ‘κ·Έλ¨μ μ΅μμ μ΄λ¦ 곡κ°
λͺ¨λλ κ°μ²΄λ‘μ λ€μν μμ±μ κ°μ§λ€.
# module_info.py
"""
μ΄ λͺ¨λμ λͺ¨λ μμ±μ μ€λͺ
νκΈ° μν μμ λͺ¨λμ
λλ€.
"""
def example_function():
return "ν¨μ μ€ν κ²°κ³Ό"
class ExampleClass:
pass
CONSTANT = 42
# λ€λ₯Έ νμΌμμ:
import module_info
# λͺ¨λ λ¬Έμμ΄(docstring) μ κ·Ό
print(module_info.__doc__)
# λͺ¨λ νμΌ κ²½λ‘
print(module_info.__file__)
# λͺ¨λ μ΄λ¦
print(module_info.__name__)
# λͺ¨λ λ΄ μ μλ μ΄λ¦ λͺ©λ‘
print(dir(module_info))
# λͺ¨λμ νΉμ μμ± νμΈ
print(hasattr(module_info, 'example_function'))
β μ£Όμ λͺ¨λ μμ±:
-
__doc__
: λͺ¨λ λ¬Έμμ΄(docstring) -
__file__
: λͺ¨λ νμΌμ κ²½λ‘ -
__name__
: λͺ¨λμ μ΄λ¦ (μ§μ μ€ν μ "main") -
__package__
: λͺ¨λμ΄ μν ν¨ν€μ§ μ΄λ¦ -
__dict__
: λͺ¨λμ μ¬λ³Ό ν μ΄λΈ (λ€μμ€νμ΄μ€) -
__loader__
: λͺ¨λμ λ‘λν λ‘λ κ°μ²΄ -
__spec__
: λͺ¨λμ λͺ μΈ μ 보
# factory_module.py
def create_adder(increment):
def add(x):
return x + increment
return add
def create_multiplier(factor):
def multiply(x):
return x * factor
return multiply
# μ¬μ© μ:
from factory_module import create_adder, create_multiplier
add_five = create_adder(5)
double = create_multiplier(2)
print(add_five(10)) # 15
print(double(10)) # 20
# singleton_module.py
class Singleton:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
if self.__class__._instance is not None:
raise RuntimeError("μ΄ ν΄λμ€λ μ±κΈν€μ
λλ€!")
self.value = 0
# μ¬μ© μ:
from singleton_module import Singleton
instance1 = Singleton.get_instance()
instance2 = Singleton.get_instance()
print(instance1 is instance2) # True
# plugin_manager.py
class PluginManager:
def __init__(self):
self.plugins = {}
def register_plugin(self, name, plugin):
self.plugins[name] = plugin
def get_plugin(self, name):
return self.plugins.get(name)
# plugin1.py
def process(data):
return f"νλ¬κ·ΈμΈ 1: {data.upper()}"
# plugin2.py
def process(data):
return f"νλ¬κ·ΈμΈ 2: {data.lower()}"
# main.py
from plugin_manager import PluginManager
import plugin1
import plugin2
manager = PluginManager()
manager.register_plugin("upper", plugin1.process)
manager.register_plugin("lower", plugin2.process)
text = "Hello World"
print(manager.get_plugin("upper")(text)) # νλ¬κ·ΈμΈ 1: HELLO WORLD
print(manager.get_plugin("lower")(text)) # νλ¬κ·ΈμΈ 2: hello world
β λͺ¨λ λμμΈ ν¨ν΄ νμ©:
- ν©ν 리 ν¨ν΄: κ°μ²΄ μμ± λ‘μ§ μΊ‘μν
- μ±κΈν€ ν¨ν΄: μ μ μν κ΄λ¦¬ λ° λ¦¬μμ€ κ³΅μ
- νλ¬κ·ΈμΈ ν¨ν΄: κΈ°λ₯ νμ₯ λ° λμ λ‘λ
- νΌμ¬λ ν¨ν΄: 볡μ‘ν νμ μμ€ν μ λ¨μν μΈν°νμ΄μ€ μ 곡
- μ΄λν° ν¨ν΄: νΈνλμ§ μλ μΈν°νμ΄μ€λ₯Ό μ°κ²°
νμ΄μ¬μ λͺ¨λμ μ΅μ΄ μν¬νΈ μ μΊμ±νμ¬ μ±λ₯μ μ΅μ ννλ€.
# λͺ¨λ μΊμ± νμΈ
import sys
# μ΄λ―Έ λ‘λλ λͺ¨λ νμΈ
print('math' in sys.modules) # False (μμ§ λ‘λλμ§ μμ)
import math
print('math' in sys.modules) # True (μ΄μ λ‘λλ¨)
# μΊμλ λͺ¨λ μ°Έμ‘°
math_cached = sys.modules['math']
print(math is math_cached) # True (λμΌν κ°μ²΄)
# λͺ¨λ λ‘λ μκ° μΈ‘μ
import time
import importlib
# μΊμ λΉμ°κΈ° (μ€μ λ‘λ κΆμ₯νμ§ μμ)
if 'random' in sys.modules:
del sys.modules['random']
# 첫 λ²μ§Έ λ‘λ μκ° μΈ‘μ
start = time.time()
import random
first_load = time.time() - start
# λ λ²μ§Έ λ‘λ μκ° μΈ‘μ
if 'random' in sys.modules:
del sys.modules['random']
start = time.time()
import random
second_load = time.time() - start
print(f"첫 λ²μ§Έ λ‘λ: {first_load:.6f}μ΄")
print(f"λ λ²μ§Έ λ‘λ: {second_load:.6f}μ΄")
β λͺ¨λ μΊμ± νΉμ§:
-
sys.modules
: μ΄λ―Έ λ‘λλ λͺ¨λμ μΊμ±νλ λμ λ리 - λ°λ³΅ μν¬νΈ μ΅μ ν: λμΌ λͺ¨λμ μ€λ³΅ λ‘λ λ°©μ§
- λ©λͺ¨λ¦¬ ν¨μ¨μ±: λͺ¨λ μ½λμ μ€λ³΅ μμ΄ μ¬μ¬μ©
- λͺ¨λ μλ³: λμΌ λͺ¨λμ κ°μ²΄ IDκ° κ°μ
- μν μν¬νΈ λ¬Έμ ν΄κ²°μ λμ
# λ°νμμ λͺ¨λ μ΄λ¦ κ²°μ
def dynamic_import(module_name):
try:
module = __import__(module_name)
print(f"{module_name} λͺ¨λμ μ±κ³΅μ μΌλ‘ μν¬νΈνμ΅λλ€.")
return module
except ImportError:
print(f"{module_name} λͺ¨λμ μ°Ύμ μ μμ΅λλ€.")
return None
# μμ :
math = dynamic_import('math')
if math:
print(math.pi)
# λ νλμ μΈ λ°©λ² (Python 3.4+)
import importlib
def modern_dynamic_import(module_name):
try:
module = importlib.import_module(module_name)
print(f"{module_name} λͺ¨λμ μ±κ³΅μ μΌλ‘ μν¬νΈνμ΅λλ€.")
return module
except ImportError:
print(f"{module_name} λͺ¨λμ μ°Ύμ μ μμ΅λλ€.")
return None
# plugins/ λλ ν 리μ λͺ¨λ λͺ¨λ μλ λ‘λ
import os
import importlib
def load_plugins(plugin_dir='plugins'):
plugins = {}
# νλ¬κ·ΈμΈ λλ ν λ¦¬κ° μ‘΄μ¬νλμ§ νμΈ
if not os.path.exists(plugin_dir):
return plugins
# νλ¬κ·ΈμΈ λλ ν 리μ λͺ¨λ Python νμΌ νμ
for filename in os.listdir(plugin_dir):
if filename.endswith('.py') and not filename.startswith('__'):
module_name = filename[:-3] # .py νμ₯μ μ κ±°
# λͺ¨λ λ‘λ
module_path = f"{plugin_dir}.{module_name}"
try:
module = importlib.import_module(module_path)
# λͺ¨λμ΄ μ¬λ°λ₯Έ μΈν°νμ΄μ€λ₯Ό κ°μ§κ³ μλμ§ νμΈ
if hasattr(module, 'run'):
plugins[module_name] = module
print(f"νλ¬κ·ΈμΈ '{module_name}' λ‘λλ¨")
except ImportError as e:
print(f"νλ¬κ·ΈμΈ '{module_name}' λ‘λ μ€ν¨: {e}")
return plugins
# λͺ¨λμ λͺ¨λ ν¨μ λͺ©λ‘ μΆλ ₯
import inspect
def list_module_functions(module):
functions = []
for name, obj in inspect.getmembers(module, inspect.isfunction):
# ν΄λΉ λͺ¨λμ μ§μ μ μλ ν¨μλ§ νν°λ§
if obj.__module__ == module.__name__:
functions.append(name)
return functions
# μμ :
import math
print(list_module_functions(math))
# λͺ¨λ ν΄λμ€ κ²μ¬
def list_module_classes(module):
classes = []
for name, obj in inspect.getmembers(module, inspect.isclass):
if obj.__module__ == module.__name__:
classes.append(name)
return classes
# ν¨μ μκ·Έλμ² κ²μ¬
def get_function_info(func):
sig = inspect.signature(func)
return {
'name': func.__name__,
'doc': func.__doc__,
'parameters': list(sig.parameters.keys()),
'return_annotation': sig.return_annotation
}
β κ³ κΈ λͺ¨λ κΈ°λ² νμ©:
- λμ μν¬νΈ: λ°νμμ νμν λͺ¨λ κ²°μ λ° λ‘λ
- λͺ¨λ μλ λ°κ²¬: νλ¬κ·ΈμΈ ꡬ쑰 ꡬν
- μΈνΈλ‘μ€νμ : λͺ¨λ ꡬ쑰μ λ΄μ© λμ λΆμ
- λ©ννλ‘κ·Έλλ°: λͺ¨λμ νμ©ν μ½λ μμ± λ° λ³ν
- μ§μ° μν¬νΈ: μ±λ₯ ν₯μμ μν νμ μμ μ μν¬νΈ
β λͺ¨λ² μ¬λ‘:
- λͺ¨λλͺ μ μλ¬Έμμ μΈλμ€μ½μ΄ μ¬μ©: κ°λ μ± λμ μ΄λ¦ μ ν
- μν μν¬νΈ νΌνκΈ°: λͺ¨λ κ° μνΈ μμ‘΄μ± μ κ±°
- νμν κ²λ§ μν¬νΈνκΈ°:
from module import *
μ§μ - μλ κ²½λ‘ μν¬νΈ μ£Όμ: λͺ νν κ²½λ‘ μ§μ μΌλ‘ νΌλ λ°©μ§
-
__init__.py
νμ©νκΈ°: ν¨ν€μ§ μ΄κΈ°ν λ° κ³΅κ° API μ μ - λͺ¨λ λ¬Έμν: κ° λͺ¨λμ μ μ ν docstring μΆκ°
- μμ‘΄μ± μ΅μν: νμν μ΅μνμ μΈλΆ λͺ¨λλ§ μ¬μ©
- ν μ€νΈ κ°λ₯ν μ€κ³: λͺ¨λμ΄ λ 립μ μΌλ‘ ν μ€νΈ κ°λ₯νλλ‘ κ΅¬μ±