에듀테크 프로젝트 대시보드
매개변수 심화 (*args, **kwargs)
* 는 위치 인자를, ** 는 키워드 인자를 묶고 풉니다.
def total(*nums): # nums 는 튜플
return sum(nums)
total(1, 2, 3) # => 6
total() # => 0
def log(level, *messages):
for m in messages:
print(f"[{level}] {m}")def make_user(**fields): # fields 는 dict
return fields
make_user(name="김", age=20) # => {'name': '김', 'age': 20}
def configure(debug=False, **extra):
print(debug, extra)
configure(debug=True, host="x", port=80)
# True {'host': 'x', 'port': 80}def point(x, y, z): ...
coords = (1, 2, 3)
point(*coords) # point(1, 2, 3)
opts = {"x": 1, "y": 2, "z": 3}
point(**opts) # point(x=1, y=2, z=3)
# 리스트/딕셔너리 합치기에도 사용
merged = [*a, *b]
combined = {**defaults, **overrides}def f(pos1, pos2, /, normal, *, kw1, kw2):
...
# |--------| |------| |--------|
# 위치 전용 일반 키워드 전용
# / 앞: 위치로만 전달 가능 (이름으로 못 넘김)
# * 뒤: 키워드로만 전달 가능
def create(name, *, admin=False): # admin 은 명시적으로만
...
create("김", admin=True) # OK
# create("김", True) # TypeErrordef retry(func, *args, **kwargs):
for _ in range(3):
try:
return func(*args, **kwargs)
except Exception:
continue
raise RuntimeError("3회 실패")
retry(requests.get, url, timeout=5)*args 는 튜플, **kwargs 는 dict*/** = 모으기, 호출부의 */** = 풀기