pydantic circular references

x·2021년 5월 2일
0

다음과 같은 에러를 마주했다. 서로 다른 파일에서 class를 가져다 type hinting을 해야하는 상황이었다.
pydantic.errors.ConfigError: field "" not yet prepared so type is still a ForwardRef, you might need to call Model.update_forward_refs().

아래 방법으로도 해결되지 않는 문제였다.

from __future__ import annotations

if TYPE_CHECKING:
    import some_module

에러 메시지에서 알려주듯이 update_forward_refs를 호출해야 했다. 문제는 import를 먼저 하는 바람에 update_forward_refs 메서드를 호출해도 소용이 없었다.

type hinting을 문자열로 처리한다. 순환 참조되는 class import를 하단에 하고 update_forward_refs를 호출한다. 이렇게 되면 실제 모델이 생성될 때 type hint에 있는 모델을 참조하지 않아 순환 참조를 해결할 수 있다.

update_forward_refs의 역할은 문자열로 선참조된 것을 다시 class를 참조하도록 해주는 것 같다. 결국 모델 생성 시 순환 참조를 일으키는 class를 문자열로 퉁치고 생성된 후에 제대로된 class를 가져오는 것 같다.

참고
Postponed annotations

0개의 댓글