내부 상태를 관리하려는 경우, 프로필 사진의 상태를 관리하기 위해 defaultdict를 쓸 수 있다고 가정할 수도 있다. 다음 코드는 이전 예제와 똑같은 로직을 도우미 함수와 defaultdict 클래스를 사용해 작성한 것이다.
from collections import defaultdict
def open_picture(profile_path):
try:
return open(profile_path, "a+b")
except OSError:
print(f"파일을 열 수 없음: {profile_path}")
raise
pictures = defaultdict(open_picture)
handle = pictures[path]
handle.seek(0)
image_data = handle.read()
>>>
Traceback ...
TypeError: open_picture() missing 1 required positional
argument: 'profile_path'