PHpullh
학습 라이브러리/Python/클로저 & 제너레이터

PYTHON · 함수

클로저 & 제너레이터

클로저로 상태를 캡처하고, yield로 메모리 효율적인 이터레이터를 만듭니다.

함수중급closurenonlocalgeneratoryieldyield from

핵심 설명

클로저로 상태를 캡처하고, yield로 메모리 효율적인 이터레이터를 만듭니다.

Python code

# 클로저 — 외부 함수의 변수를 기억
def make_counter(start: int = 0):
    count = start

    def counter():
        nonlocal count   # 외부 변수 수정하려면 nonlocal 필요
        count += 1
        return count

    return counter

c1 = make_counter()
c2 = make_counter(10)
print(c1(), c1(), c1())   # 1 2 3
print(c2(), c2())          # 11 12 (독립적)

# 제너레이터 함수
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# 제너레이터는 next() 호출 시에만 실행됨 (lazy)
gen = fibonacci()
fibs = [next(gen) for _ in range(10)]
print(fibs)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# yield from — 하위 제너레이터 위임
def chain(*iterables):
    for it in iterables:
        yield from it

list(chain([1,2], [3,4], [5]))  # [1,2,3,4,5]

# 제너레이터 파이프라인
def read_lines(text):
    yield from text.splitlines()

def filter_empty(lines):
    yield from (l for l in lines if l.strip())

def to_upper(lines):
    yield from (l.upper() for l in lines)

text = "hello

world
python"
result = list(to_upper(filter_empty(read_lines(text))))

학습 팁

yield from은 하위 제너레이터를 완전히 위임합니다. 재귀 제너레이터나 파이프라인 구성에 적합합니다.

주의할 점

nonlocal 없이 클로저 내부에서 외부 변수에 대입하면 새 지역 변수가 만들어집니다. UnboundLocalError의 흔한 원인입니다.

자주 묻는 질문

클로저 & 제너레이터란 무엇인가요?

클로저로 상태를 캡처하고, yield 로 메모리 효율적인 이터레이터를 만듭니다.

클로저 & 제너레이터 학습 시 주의할 점은 무엇인가요?

nonlocal 없이 클로저 내부에서 외부 변수에 대입하면 새 지역 변수가 만들어집니다. UnboundLocalError 의 흔한 원인입니다.