Better way 19 ν¨μκ° μ¬λ¬ κ°μ λ°ννλ κ²½μ° μ λλ‘ λ€ κ° μ΄μμ μΈν¨νΉνμ§ λ§λΌ
ν¨μκ° μ¬λ¬ κ°μ λ°ννλ κ²½μ°, μΈν¨νΉ κ³Όμ μμ μ€λ₯κ° μΌμ΄λκΈ° μ½λ€.
# μμ’μ μμ - μΈν¨νΉνλ μΈμμμ μμκ° λ°λμμ λ, μ€λ₯λ₯Ό μΈμ§νκΈ° μ΄λ ΅λ€
def get_stats(numbers):
minimum = min(numbers)
maximum = max(numbers)
count = len(numbers)
average = sum(numbers) / count
return minimum, maximum, count, average
# μ μμ μΌλ‘ νΈμΆ
minimum, maximum, count, average = get_stats([1,2,3,4])
# average, count μμλ₯Ό μλͺ» νΈμΆ - μ€λ₯λ₯Ό μΈμ§νκΈ° μ΄λ €μ
minimum, maximum, average, count = get_stats([1,2,3,4])
ν΄κ²° λ°©λ² 1. namedtuple μ¬μ©
# μ’μ μμ 1 - namedtuple
from collections import namedtuple
# namedtuple μ μ
Stats = namedtuple('Stats', ['minimum', 'maximum', 'count', 'average'])
def get_stats(numbers):
minimum = min(numbers)
maximum = max(numbers)
count = len(numbers)
average = sum(numbers) / count
return Stats(minimum, maximum, count, average)
# νΈμΆ μ, μ΄λ¦μΌλ‘ κ°μ μ κ·Όνμ¬ μμλ₯Ό μ κ²½ μΈ νμ μμ
stats = get_stats([1, 2, 3, 4])
print(stats.minimum) # 1
print(stats.maximum) # 4
print(stats.count) # 4
print(stats.average) # 2.5
ν΄κ²° λ°©λ² 2. dataclass μ¬μ©
# μ’μ μμ 2 - dataclass μ¬μ©
from dataclasses import dataclass
# dataclass μ μ
@dataclass
class Stats:
minimum: int
maximum: int
count: int
average: float
def get_stats(numbers):
minimum = min(numbers)
maximum = max(numbers)
count = len(numbers)
average = sum(numbers) / count
return Stats(minimum, maximum, count, average)
# νΈμΆ μ, κ°μ²΄μ μμ±μΌλ‘ μ κ·Ό
stats = get_stats([1, 2, 3, 4])
print(stats.minimum) # 1
print(stats.maximum) # 4
print(stats.count) # 4
print(stats.average) # 2.5
namedtupleκ³Ό dataclassμ μ°¨μ΄
νΉμ± | namedtuple | dataclass |
λ³κ²½ κ°λ₯ μ¬λΆ | λΆλ³(immutable) κ°μ²΄ | κΈ°λ³Έμ μΌλ‘ κ°λ³(mutable) κ°μ²΄, frozen=Trueλ‘ λΆλ³ μ€μ κ°λ₯ |
λ©μλ μΆκ° | λ©μλ μΆκ° λΆκ° | λ©μλ μΆκ° κ°λ₯ |
μμ μ§μ | μμ λΆκ° | μμ κ°λ₯ |
κΈ°λ³Έ μμ±μ | μλ μμ±λ¨ | μλ μμ±λ¨ |
λΉκ΅ μ°μ°μ | μλ μμ±λ¨ (__eq__ λ±) | μλ μμ±λ¨ (__eq__ λ±) |
__repr__ | μλ μμ±λ¨ | μλ μμ±λ¨ |
κΈ°ν νΉμ§ | ννκ³Ό νΈνλλ©° λ©λͺ¨λ¦¬ ν¨μ¨μ | κ°μ²΄ μ§ν₯μ μ΄λ©° νμ₯μ± μμ |
Better way 20 Noneμ λ°νν기보λ€λ μμΈλ₯Ό λ°μμμΌλΌ
# μ μ’μ μμ - μ€λ₯ μν©μμ Noneλ₯Ό λ°ν
def safe_divide(a, b):
if b == 0:
return None # 0μΌλ‘ λλλ κ²½μ° None λ°ν
return a / b
result = safe_divide(10, 0)
if result is None:
print("Error: Division by zero")
else:
print("Result:", result)
- μμΈ μν©μμ Noneλ₯Ό λ°ννλ©΄ νΈμΆνλ μͺ½μμ Noneμ κ²μ¦νλ κ²μ΄ λΆμμ°μ€λ½λ€.
- λν μ¬λ¬ μμΈλ₯Ό None νλλ‘ νννμ¬ λ°ννλ©΄ μμΈλ₯Ό νΉμ νκΈ° μ΄λ ΅λ€.
# μ’μ μμ - μ€λ₯ μν©μμ μμΈ λ°μ
def safe_divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = safe_divide(10, 0)
print("Result:", result)
except ZeroDivisionError as e:
print("Error:", e)
Better way 21 λ³μ μμκ³Ό ν΄λ‘μ μ μνΈμμ© λ°©μμ μ΄ν΄νλΌ
νμ΄μ¬ μΈν°ν리ν°κ° λ³μλ₯Ό μ°Ύλ μμ
- νμ¬ ν¨μμ μμ
- νμ¬ ν¨μλ₯Ό λλ¬μΌ μμ
- νμ¬ μ½λκ° λ€μ΄ μλ λͺ¨λμ μμ - μ μ μμ(global)
- λ΄μ₯ μμ (built-in-scope) - len, str λ±μ ν¨μκ° λ€μ΄ μλ μμ
def sort_priority(values, group):
def helper(x):
if x in group:
return (0,x)
return (1,x)
values.sort(key=helper)
helper ν¨μμμ groupμ΄ μ μΈλμ΄ μμ§ μμ§λ§ μλ¬κ° λ°μνμ§ μλλ€
μλνλ©΄ "νμ¬ ν¨μλ₯Ό λλ¬μΌ μμ" μμ group λ³μλ₯Ό μ°Ύμ μ μκΈ° λλ¬Έ -> νμ΄μ¬μ΄ ν΄λ‘μ λ₯Ό μ§μνκΈ° λλ¬Έ
def sort_priority2(numbers, group):
found = False
def helper(x):
if x in group:
found = True
return (0, x)
return (1,x)
numbers.sort(key=helper)
return found
μμ ν¨μλ μ μμ μΌλ‘ λμνμ§ μλλ€. (κ°λ°μ μλλλ‘ λμ x)
μμ μ§μ λ²κ·Έ(scoping bug)κ° λ°μνκΈ° λλ¬Έμ΄λ€.
helper ν¨μμ "found = True" ꡬ문μ sort_priority2μμ μ μΈλμ΄ μλ found λ³μμ Trueμ ν λΉνλ κ²μ΄ μλ helper ν¨μ λ΄μμ found λΌλ λ³μλ₯Ό μλ‘ λ§λ€κ³ Trueλ₯Ό ν λΉνκΈ° λλ¬Έμ΄λ€.
def sort_priority3(numbers, group):
found = False
def helper(x):
if x in group:
nonlocal found = True
return (0, x)
return (1,x)
numbers.sort(key=helper)
return found
nonlocal ν€μλλ₯Ό μ¬μ©νλ©΄ sort_priority3 μ foundμ κ°μ΄ μ μμ μΌλ‘ ν λΉν μ μμ§λ§, nonlocal ν€μλλ μ¬μ©νμ§ λ§μ ν¨μμ λμμ μ΄ν΄νλ λ°, μ΄λ €μμ§λ€.
κ΅¬λΆ | global | nonlocal |
μ¬μ© λͺ©μ | μ μ λ³μλ₯Ό ν¨μ λ΄λΆμμ μμ ν λ μ¬μ© | μ€μ²© ν¨μ λ΄λΆμμ λ°κΉ₯ ν¨μμ λ³μλ₯Ό μμ ν λ μ¬μ© |
μ μ© λμ | μ μ λ³μ | νμ¬ ν¨μμ λ°κΉ₯ ν¨μ(non-global)μ μ§μ λ³μ |
μ μΈ μμΉ | ν¨μ λ΄λΆ | μ€μ²© ν¨μ λ΄λΆ |
λ³μ μμ± μ¬λΆ | κΈ°μ‘΄ μ μ λ³μλ₯Ό μ¬μ© (μμΌλ©΄ μ€λ₯ λ°μ) | κΈ°μ‘΄ λ³μλ₯Ό μ¬μ© (μμΌλ©΄ μ€λ₯ λ°μ) |
Better way 22 λ³μ μμΉ μΈμλ₯Ό μ¬μ©ν΄ μκ°μ μΈ μ‘μμ μ€μ¬λΌ
μλ₯Ό λ€λ©΄ λ‘κ·Έλ₯Ό λ¨κΈ°λ ν¨μλΌκ³ νμ
# μ μ’μ μμ
def log(message, values):
if not values:
print(message)
else:
values_str = ', '.join(str(x) for x in values)
print(f'{message}: {values_str}')
log('λ΄ μ«μλ', [1,2])
log('μλ
', []) # valuesκ° μλ κ²½μ°μλ λΉ λ¦¬μ€νΈλ₯Ό λ£μ΄μ€μΌν¨
>>>
λ΄ μ«μλ: 1, 2
μλ
# μ’μ μμ - * ν€μλ μ¬μ©
def log(message, *values): # μ μΌνκ² λ¬λΌμ§ λΆλΆ
if not values:
print(message)
else:
values_str = ', '.join(str(x) for x in values)
print(f'{message}: {values_str}')
log('λ΄ μ«μλ', 1, 2)
log('μλ
') # valuesκ° μλ κ²½μ°μλ μλ΅ κ°λ₯
>>>
λ΄ μ«μλ: 1, 2
μλ
Better Way 25: μμΉ μ μ© μΈμ λλ ν€μλ μ μ© μΈμλ₯Ό μ¬μ©ν΄ ν¨μ νΈμΆμ λͺ ννκ² λ§λ€λΌ
ν¨μ νΈμΆμ΄ 볡μ‘νκ³ νΉμ μΈμλ₯Ό ν€μλ μ μ© μΈμλ‘ λ°κΎΈμ΄ ν¨μ νΈμΆμ λͺ ννκ² ν μ μλ€.
# μ μ’μ μμ
def move(x, y, speed):
print(f"Moving to ({x}, {y}) at speed {speed}")
move(10, 20, 5) # μλκ° μμΉμΈμ§ ν·κ°λ¦΄ μ μμ
# μ’μ μμ - * λ₯Ό ν΅ν΄ ν€μλ μ μ© μΈμ μ€μ μ΄ κ°λ₯
def move(x, y, *, speed):
print(f"Moving to ({x}, {y}) at speed {speed}")
move(10, 20, 5)
>>>
TypeError: move() takes 2 positional arguments but 3 were given
move(10, 20, speed=5) # speed ν€μλ μΈμ μ¬μ©
>>>
Moving to (10, 20) at speed 5
Better way 26 functools.wrapμ μ¬μ©ν΄ ν¨μ λ°μ½λ μ΄ν°λ₯Ό μ μνλΌ
νμ΄μ¬μμλ λ°μ½λ μ΄ν°λ₯Ό μ μν μ μλ λ°, μ΄ λ functools.wrapμ μ¬μ©νμ
# μ μ’μ μμ - λ©ν λ°μ΄ν°κ° μ¬λΌμ§ (λλ²κ±°μ κ°μ΄ μΈνΈλ‘μ€νμ
νλ λꡬμμ λ¬Έμ κ° λ°μ)
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
return func(*args, **kwargs)
return wrapper
@my_decorator
def say_hello():
"""Returns a greeting."""
print("Hello!")
print(say_hello.__name__) # wrapper
print(say_hello.__doc__) # None (λ¬Έμ λ¬Έμμ΄μ΄ μ¬λΌμ§)
# μ’μ μμ
from functools import wraps
def my_decorator(func):
@wraps(func) # μλ³Έ ν¨μμ λ©νλ°μ΄ν° μ μ§
def wrapper(*args, **kwargs):
print("Before function call")
return func(*args, **kwargs)
return wrapper
@my_decorator
def say_hello():
"""Returns a greeting."""
print("Hello!")
print(say_hello.__name__) # say_hello
print(say_hello.__doc__) # "Returns a greeting."
Effective Python 2nd μ΄νν°λΈ νμ΄μ¬ : νμ΄μ¬ μ½λ©μ κΈ°μ : λ€μ΄λ² λμ
λ€μ΄λ² λμ μμΈμ 보λ₯Ό μ 곡ν©λλ€.
search.shopping.naver.com
'π Python' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
μ΄νν°λΈ νμ΄μ¬ 5μ₯ - ν΄λμ€μ μΈν°νμ΄μ€ (0) | 2025.03.21 |
---|---|
μ΄νν°λΈ νμ΄μ¬ 4μ₯ - μ»΄ν리ν¨μ κ³Ό μ λλ μ΄ν° (0) | 2025.03.18 |
μ΄νν°λΈ νμ΄μ¬ 2μ₯ - 리μ€νΈμ λμ λ리 (0) | 2025.03.12 |
μ΄νν°λΈ νμ΄μ¬ 1μ₯ - νμ΄μ¬λ΅κ² μκ°νκΈ° (0) | 2025.03.06 |
[Python] *, ** μ¬μ©λ² (0) | 2025.02.18 |