Skip to content

Commit

Permalink
Optimize recursion detection by stopping on the second visit for the …
Browse files Browse the repository at this point in the history
…same object (#7160)

Co-authored-by: Mihai Ciucu <mihai@blink.net>
  • Loading branch information
mciucu and Mihai Ciucu committed Aug 17, 2023
1 parent 04150b1 commit 78e2c2c
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pydantic/_internal/_core_utils.py
Expand Up @@ -467,8 +467,12 @@ def count_refs(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreS
return recurse(s, count_refs)
ref = s['schema_ref']
ref_counts[ref] += 1
if current_recursion_ref_count[ref] != 0:
involved_in_recursion[ref] = True

if ref_counts[ref] >= 2:
# If this model is involved in a recursion this should be detected
# on its second encounter, we can safely stop the walk here.
if current_recursion_ref_count[ref] != 0:
involved_in_recursion[ref] = True
return s

current_recursion_ref_count[ref] += 1
Expand Down

0 comments on commit 78e2c2c

Please sign in to comment.