[Python] MappingProxyType
2022. 12. 7. 22:07
읽기 전용 dict
즉, 수정 불가한 dict을 가능하게 해주는 MappingProxyType을 사용해보자.
from types import MappingProxyType
dic = {'k': 'v'}
dic_frozen = MappingProxyType(dic)
dic['new_k'] = 'new_v'
dic_frozen['new_k'] = 'new_v' # 오류

dic_frozen은 읽기 전용 딕셔너리이므로 새로운값을 추가하거나 수정할 수 없다.
원본 데이터가 중요할 때 사용하기 유용하다!
frozenset
set에도 frozenset을 통해 유사한 기능을 적용할 수 있다.
set_1 = {'가', '나', '다'}
set_2 = set(['가', '나', '다'])
frozen_set_2 = frozenset(set_2)
print(set_1, set_2, frozen_set_2)
set_1.add('라')
frozen_set_2.add('라')

frozenset 함수안에 set을 넘겨주어 수정이 불가한 읽기 전용 set을 만들 수 있다.
앞선 읽기 전용 딕셔너리와 같이 새로운 값을 추가하거나 수정할 수 없다.
'Python > 파이썬 중급' 카테고리의 다른 글
| [Python] mutable(가변 객체), immutable(불변 객체) (0) | 2022.12.08 |
|---|---|
| [Python] map, filter 함수 (0) | 2022.12.07 |
| [Python] 네임드 튜플 (namedtuple) (0) | 2022.12.06 |
| [Python] 매직 메소드 (0) | 2022.11.30 |
| [Python] 데코레이터 심화 (0) | 2022.11.29 |