collections.namedtuple

collections.namedtuple

1. namedtuple이란

명칭 그대로 index(idx)로만 값(value)에 접근 가능한 기본 튜플(basic Tuple)과는 다르게 키(key)값으로 접근이 가능하도록 제공한다. 키(namedtuple에서는 field_names)를 가지고 값에 접근이 가능한 점이 딕셔너리(dict)타입과 비슷하다 할 수 있다. namedtuple()에 대한 자세한 내용은 docs.python.org 에서 확인할 수 있다.

namedtuple()은 collections.namedtuple(typename, field_names, verbose=False, rename=False)을 입력값으로 받으며, field_names 를 통해 namedtuple()의 키 즉, 필드명(fieldname)을 정의할 수 있다. 필드명을 정의할 때에는 필드사이에 빈칸(whitespace)이나 ‘,’ 로 구분 해준다. 예를들어 필드명 x 와 y 를 지정할 경우 ‘x y’ 나 ‘x, y’와 같이 입력해야한다. 다른방법으로는 [‘x’, ‘y’]와 같이 리스트(list)형식으로 필드명을 지정해줄 수 있다.

1.1. tuple vs namedtuple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import namedtuple


Point = namedtuple('Point', 'x, y')

pt1 = Point(10, 20)
pt2 = Point(20, 40)

tp1 = (10, 20)
tp2 = (20, 40)

print(pt1, pt2)
print(pt1.x, pt1.y)

print(tp1, tp2)
print(tp1[0], tp1[1])

위의 소스를 실행시켜 보면, 접근 방식의 차이가 분명하다.


namedtuple vs tuple

  • 차이점
    • namedtuple 의 경우엔 딕셔너리와 같은 형태로 내부 값에 접근
    • tuple 의 경우엔 인덱스 요소 접근 방식으로 내부 값에 접근

2. namedtuple 함수

2.1. _make()

1
2
3
4
5
6
7
8
from collections import namedtuple


Point = namedtuple('Point', 'x, y')

location = [1, 5]
pt3 = Point._make(location)
print(pt3)

정의된 namedtuple 객체를 이용하여, _make() 함수를 활용한 객체 생성도 가능하다.

2.2. _replace()

1
2
3
4
5
6
7
8
from collections import namedtuple


Point = namedtuple('Point', 'x, y')

location = [1, 5]
pt3 = Point._make(location)
print(pt3._replace(x=100))

튜플은 기본적으로 내부 요소의 값의 변경이 불가능하지만, 기존에 가지고 있던 요소별 값 중 일부를 변경하여 새로운 객체로 변환이 가능하게 도와주는 함수라 볼 수 있다.

2.3. _fields

1
2
3
4
5
6
7
8
9
from collections import namedtuple


Point = namedtuple('Point', 'x, y')
print(Point._fields)

Color = namedtuple('Color', 'red green blue')
Pixel = namedtuple('Pixel', Point._fields + Color._fields)
print(Pixel(11, 22, 128, 255, 0))

namedtuple 로 정의된 객체의 필드를 확인할 수 있는 _fields 이다.

2.4. _fields_defaults

1
2
3
4
5
6
7
8
9
10
11
from collections import namedtuple


Account = namedtuple('Account', ['type', 'balance'], defaults=[123456,999])
print(Account._fields_defaults)

account = Account()
print(account)

account = Account('premium')
print(account)

2.5. rename

1
2
3
4
5
6
7
8
from collections import namedtuple


# 실행 시 에러 발생
use_built_in_keyword = namedtuple('Account', ['type', 'balance', 'class'])

use_built_in_keyword = namedtuple('use_built_in_keyword', ['type', 'balance', 'class'], rename=True)
print(use_built_in_keyword('a', 'b', 'c'))


namedtuple rename


namedtuple 을 이용하여, 객체 생성시 정의된 내부 키워드 ‘class’ 와 같은 명칭을 사용할 경우 에러가 발생한다. (default: rename=False)
명칭을 사용할 때에는, 정의된 키워드를 피하는 것을 추천하나 굳이 사용해야하는 경우 rename=True 를 써준다면 내부적으로 해당 명칭을 변경시켜주어 충돌을 피할 수 있다.

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×