특정 키와 값의 타입을 제한하는 딕셔너리 (TypedDict)
이 예제에서는 딕셔너리에 추가되는 키와 값의 타입을 제한하여, 특정한 타입의 키와 값만 허용하도록 합니다.
코드 설명
__init__: 키와 값의 타입을 정의합니다.
__setitem__: 키와 값의 타입을 검사하여 일치하지 않으면 예외를 발생시킵니다.
update: 모든 항목의 타입을 검사하여 제한을 적용합니다.
코드 샘플
python
class TypedDict(dict):
def **init**(self, key\_type, value\_type, _args, \*_kwargs):
self.key\_type = key\_type
self.value\_type = value\_type
super().**init**(_args, \*_kwargs)
for key, value in self.items():
self.\_check\_types(key, value)
def _check_types(self, key, value):
if not isinstance(key, self.key_type):
raise TypeError(f"Key '{key}' is not of type {self.key_type.__name__}")
if not isinstance(value, self.value_type):
raise TypeError(f"Value '{value}' for key '{key}' is not of type {self.value_type.__name__}")
def __setitem__(self, key, value):
self._check_types(key, value)
super().__setitem__(key, value)
def update(self, *args, **kwargs):
if args:
if isinstance(args[0], dict):
items = args[0].items()
elif isinstance(args[0], (list, tuple)):
items = args[0]
else:
raise TypeError("Invalid argument type for update")
for key, value in items:
self._check_types(key, value)
for key, value in kwargs.items():
self._check_types(key, value)
super().update(*args, **kwargs)
사용 예제
try:
typed\_dict = TypedDict(str, int, {'a': 1, 'b': 2})
print(typed\_dict) # 출력: {'a': 1, 'b': 2}
# 올바른 타입의 값 추가
typed_dict['c'] = 3
print(typed_dict) # 출력: {'a': 1, 'b': 2, 'c': 3}
# 잘못된 타입의 키 추가 시도
typed_dict[4] = 4 # TypeError 발생
except TypeError as e:
print(e) # 출력: Key '4' is not of type str
try:
\# 잘못된 타입의 값 추가 시도
typed\_dict\['d'\] = 'four' # TypeError 발생
except TypeError as e:
print(e) # 출력: Value 'four' for key 'd' is not of type int
try:
\# update 메서드로 올바르지 않은 타입의 값 추가 시도
typed\_dict.update({'e': 5, 'f': 'six'}) # TypeError 발생
except TypeError as e:
print(e) # 출력: Value 'six' for key 'f' is not of type int
출력 결과
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3}
"Key '4' is not of type str"
"Value 'four' for key 'd' is not of type int"
"Value 'six' for key 'f' is not of type int"
'실용적인 코드 샘플' 카테고리의 다른 글
[실용적인 코드 샘플] 고정 크기 리스트 자료구조 (FixedSizeList) (0) | 2024.10.18 |
---|---|
[실용적인 코드 샘플] 제너릭을 이용한 `Triple` 자료구조 1 (2) | 2024.10.16 |
[실용적인 코드 샘플] 최대 크기를 가지는 딕셔너리 (`LimitedSizeDict`) (0) | 2024.10.16 |
[실용적인 코드 샘플] 읽기 전용 딕셔너리(ReadOnlyDict) (2) | 2024.10.16 |
[실용적인 코드 샘플] 제너릭을 이용한 `Pair` 클래스 1 (0) | 2024.10.15 |