> ## Content Index
> Fetch the complete content index at: https://bongholee.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# NamedTuple을 이용한 가독성 개선 목적의 리팩토링
- URL: https://bongholee.com/namedtupleeul-iyonghan-gadogseong-gaeseon-mogjeogyi-ripaegtoring/
- Published: 2024-08-19T02:06:51.000Z
- Updated: 2024-08-19T02:06:51.000Z
- Author: Bongho Lee
- Tags: Python, #Import 2026-11-22 06:32

## Tuple Unpacking 이란

- 하나의 튜플(tuple)을 여러 개의 변수로 분해하여 사용하는 것

```python
a, b, c = (1, 2, 3)

```

## 문제점

- 변수 갯수가 맞지 않을 때

```python
# 예시 코드: 변수 갯수 불일치
result = (0.8, 0.1)
accuracy, loss, precision = result  # ValueError 발생

```

- 의미없는 변수 이름을 사용시 → 이후에 가독성 이슈

```python
# 예시 코드: 의미 없는 변수 이름
a, b, c = model.predict(X_test)

```

## 리팩토링

- 명시적인 변수 명 사용

```python
# 리팩토링 코드: 명시적인 변수 이름 사용
accuracy, loss = model.predict(X_test)[:2]
precision = model.predict(X_test)[2]  # precision을 나중에 따로 할당

```

- NamedTuple 사용
- Dict를 써도 되나, 아래의 경우를 고려시 Named Tuple이 더 나을 수 있음  
  - 데이터가 고정된 구조를 가지고 있으며, 데이터가 불변이어야 할 때
  - 성능(특히 메모리 사용량 및 접근 속도)이 중요한 경우
  - 코드의 가독성과 명확성이 중요한 경우

```python
from collections import namedtuple

# NamedTuple 사용 예시
Prediction = namedtuple('Prediction', ['accuracy', 'loss', 'precision'])
result = Prediction(accuracy=0.8, loss=0.1, precision=0.85)

print(result.accuracy)  # 0.8
print(result.loss)      # 0.1
print(result.precision) # 0.85

```

- Dictionary 사용
- Dict를 사용하는게 더 나을 경우  
  - 데이터 구조가 유연하게 변경될 가능성이 있을 때
  - 키-값 쌍을 동적으로 추가, 수정, 삭제할 필요가 있을 때
  - Python의 다른 라이브러리 및 함수와의 통합이 중요한 경우

```python
# 딕셔너리 사용 예시
result = {'accuracy': 0.8, 'loss': 0.1, 'precision': 0.85}

print(result['accuracy'])  # 0.8
print(result['loss'])      # 0.1
print(result['precision']) # 0.85

```