claude-memory/graph/code-patterns/pattern-lazy-import-inside-function-body-to-break-circular-i-d637ad.md
2026-02-25 16:27:03 -06:00

1.4 KiB

id type title tags importance confidence created updated relations
d637ad5b-0ad1-4164-b737-b870fce85ae1 code_pattern Pattern: Lazy import inside function body to break circular imports
paper-dynasty
card-creation
card_builder
calcs_batter
circular_import
lazy_import
python
0.6 0.8 2026-02-25T22:26:37.747893+00:00 2026-02-25T22:27:03.733654+00:00
target type direction strength edge_id
c7623317-ea0a-4b8a-9375-65fc3aac5303 FOLLOWS outgoing 0.8 06095a46-699a-47bf-a1f1-418605b03d0f

Problem\nbatters/card_builder.py imports from batters/calcs_batter.py (needs BattingCardRatingsModel). If calcs_batter.py also imported from card_builder.py at module level, this would cause a circular ImportError.\n\n## Solution: Lazy Import Inside Function Body\npython\n# In batters/calcs_batter.py — inside get_batter_ratings():\ntry:\n from batters.card_builder import build_batter_full_cards\n vl_card, vr_card = build_batter_full_cards(...)\n vl_dict.update(vl_card.card_output())\n vr_dict.update(vr_card.card_output())\nexcept Exception as e:\n logger.warning(f'Card layout builder failed: {e}')\n\n\nSame pattern used in pitchers/calcs_pitcher.py:\npython\nfrom pitchers.card_builder import build_pitcher_full_cards\n\n\n## Why It Works\nThe import only executes when the function is called, not at module load time, so the circular dependency never materializes at import resolution.