lazy evaluation 관련한 포스팅을 보다가 해석이 안되는 복잡한? 코드를 발견했습니다. 함께 해석해봅시다.
Class LazyDict(dict):
def get(self, key, thunk=None):
return (self[key] if key in self else thunk() if callable(thunk) else
thunk)
def setdefault(self, key, thunk=None):
return (self[key] if key in self else
dict.setdefault(self, key,thunk() if callable(thunk) else
thunk))
알고 있는 지식
1. 여기서 return 뒤에 있는 ()식 전체는 리스트 컴프리헨션이 아니라 제너레이터이다.
2. callable() 전달받은 인자가 호출 가능한지 여부를 판단한다 .
궁금증
1. self[key]는 뭔가? key가 self 안에 있다면 self[key]를 가져오고 아니면 thunk()를 호출하는데 thunk를 호출할때 만약에 thunk가 호출 가능한 인자면? 그렇지 않다면?
-해결한 결론은 self[key]는 self.keys를 dictionary 버전으로 가져오는 것이다. 아니면 thunk 를 쓰는데 이걸 2중 for문 형태로 thunk가 불러 올 수 있는 거면 불러오고 아니면 thunk라고 나온다고 한다.