deep-dive2024-03-15·7 min·319/348

Python Walrus Operator (:=) 활용법

Python 3.8+의 walrus operator (:=)를 활용한 효율적인 코딩 기법을 알아봅니다.

Python Walrus Operator (:=) 활용법

Python 3.8에 도입된 walrus operator (:=)는赋值 表达式을 가능하게 하여, 표현식 내에서 값을 할당하고 동시에 사용할 수 있게 합니다.

Environment

$ python --version
Python 3.11.5

$ python -c "x := 5; print(x)" 2>&1 || echo "Need Python 3.8+"
5

Problem: 반복적인 계산과 변수 할당

# Before walrus operator - verbose code
data = get_data()
if data:
    process(data)

# Or with function calls
result = expensive_computation()
if result is not None:
    handle_result(result)

# Complex condition with repeated computation
items = get_items()
if items and len(items) > 10:
    process_large_list(items)

Analysis: Walrus Operator 동작 원리

# Walrus operator syntax: := 
# Assigns value to variable as part of expression

# Traditional approach
n = len([1, 2, 3, 4, 5])
if n > 3:
    print(f"List has {n} items")

# With walrus operator
if (n := len([1, 2, 3, 4, 5])) > 3:
    print(f"List has {n} items")

Solution: Walrus Operator 활용 예제

While 루프에서의 활용

# Before
line = input("Enter command: ")
while line != "quit":
    process(line)
    line = input("Enter command: ")

# After - walrus operator
while (line := input("Enter command: ")) != "quit":
    process(line)

List comprehension에서의 활용

# Filter and transform in one pass
import math

numbers = [1, 4, 15, 16, 25, 36, 49, 64, 81, 100]

# Before
squares = []
for n in numbers:
    sqrt = math.isqrt(n)
    if sqrt * sqrt == n:
        squares.append(sqrt)

# After - walrus operator
squares = [sqrt for n in numbers if (sqrt := math.isqrt(n)) * sqrt == n]
print(squares)  # [1, 4, 5, 6, 7, 8, 9, 10]

조건부 표현식에서의 활용

# Before
value = get_value()
if value:
    result = process(value)
else:
    result = default_value

# After - walrus operator
result = process(value) if (value := get_value()) else default_value

정규표현식에서의 활용

import re

text = "Contact us at support@example.com or sales@company.com"

# Before
match = re.search(r'[\w.]+@[\w.]+', text)
if match:
    email = match.group()
    print(f"Found email: {email}")

# After - walrus operator
if match := re.search(r'[\w.]+@[\w.]+', text):
    print(f"Found email: {match.group()}")

중첩된 조건에서의 활용

# Complex data processing
data = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
    {"name": "David", "score": 95},
]

# Before
results = []
for item in data:
    score = item.get("score", 0)
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    else:
        grade = "C"
    results.append({"name": item["name"], "grade": grade})

# After - walrus operator
results = [
    {
        "name": item["name"],
        "grade": "A" if (score := item.get("score", 0)) >= 90
                else "B" if score >= 80
                else "C"
    }
    for item in data
]

파일 처리에서의 활용

# Before
with open("data.txt") as f:
    line = f.readline()
    while line:
        process(line)
        line = f.readline()

# After - walrus operator
with open("data.txt") as f:
    while (line := f.readline()):
        process(line)

성능 최적화

# Cache expensive computation
import functools

@functools.lru_cache(maxsize=None)
def expensive_calculation(n):
    print(f"Computing {n}...")
    return sum(i * i for i in range(n))

# Without walrus - computation happens twice
# if expensive_calculation(1000000) > 0:
#     result = expensive_calculation(1000000)  # Duplicate!

# With walrus - computation happens once
if (result := expensive_calculation(1000000)) > 0:
    print(f"Result: {result}")

Lessons Learned

  1. 가독성 향상: Walrus operator는 반복적인 할당을 줄여 코드를 더 간결하게 만듭니다.

  2. 성능 향상: 비용이 큰 계산을 한 번만 수행하도록 할 때 유용합니다.

  3. 적절한 사용: 모든 상황에 walrus operator를 사용할 필요는 없습니다. 코드 가독성이 떨어지면 사용하지 마세요.

  4. While 루프: while (line := input()) 패턴은 루프 조건과 입력을 한 줄로 처리할 때 편리합니다.

  5. Python 3.8+ 필수: Walrus operator는 Python 3.8 이상에서만 사용할 수 있습니다.


This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.