PYTHON · 함수
파이프라인 패턴
함수들을 파이프라인으로 연결하여 데이터를 순차적으로 처리하는 함수형 패턴입니다.
함수고급pipelinepipecompose함수형
핵심 설명
함수들을 파이프라인으로 연결하여 데이터를 순차적으로 처리하는 함수형 패턴입니다.
Python code
from functools import reduce
from typing import Callable, Any
# pipe: 왼쪽에서 오른쪽으로 합성
def pipe(*funcs: Callable) -> Callable:
def piped(data):
return reduce(lambda v, f: f(v), funcs, data)
return piped
# compose: 오른쪽에서 왼쪽으로 합성
def compose(*funcs: Callable) -> Callable:
return pipe(*reversed(funcs))
# 개별 변환 함수
def normalize(text: str) -> str:
return text.strip().lower()
def remove_punctuation(text: str) -> str:
return "".join(c for c in text if c.isalnum() or c.isspace())
def tokenize(text: str) -> list[str]:
return text.split()
# 파이프라인 조합
text_pipeline = pipe(normalize, remove_punctuation, tokenize)
result = text_pipeline(" Hello, World! Python 3.12 ")
print(result) # ['hello', 'world', 'python', '312']
# compose로 같은 결과
process = compose(tokenize, remove_punctuation, normalize)
print(process(" Test, Data! ")) # ['test', 'data']학습 팁
pipe는 데이터 흐름 순서대로, compose는 수학적 합성 순서(g∘f)로 함수를 연결합니다.
주의할 점
파이프라인의 각 함수는 이전 함수의 출력 타입을 입력으로 받아야 합니다. 타입 불일치 시 런타임 오류가 발생합니다.
자주 묻는 질문
파이프라인 패턴란 무엇인가요?
함수들을 파이프라인으로 연결하여 데이터를 순차적으로 처리하는 함수형 패턴입니다.
파이프라인 패턴 학습 시 주의할 점은 무엇인가요?
파이프라인의 각 함수는 이전 함수의 출력 타입을 입력으로 받아야 합니다. 타입 불일치 시 런타임 오류가 발생합니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.