Skip to content

Fix generic type import with module path#2858

Merged
koxudaxi merged 1 commit intomainfrom
fix/generic-type-import
Dec 30, 2025
Merged

Fix generic type import with module path#2858
koxudaxi merged 1 commit intomainfrom
fix/generic-type-import

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Dec 30, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced generic type representation to include full module qualification for custom origins.
    • Improved handling and import resolution for custom generic types in generated code.
  • Tests

    • Added test coverage for custom generic type import paths.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 30, 2025

📝 Walkthrough

Walkthrough

Enhanced the _get_origin_name function to return fully qualified module paths for non-standard generic origins. Added test data structures for custom generic types and introduced a test to verify these types are imported with proper module qualification.

Changes

Cohort / File(s) Summary
Core Type Origin Handling
src/datamodel_code_generator/__main__.py
Modified _get_origin_name() to emit module-qualified names (e.g., module.ClassName) for custom origins while excluding builtins, typing, and collections.abc; altered string representation of generic type origins
Test Data Models
tests/data/python/input_model/pydantic_models.py
Added TypeVar declarations (TK, TV), introduced CustomGenericDict class inheriting from UserDict[TK, TV] with Generic support, and created ModelWithCustomGeneric Pydantic model with custom dictionary fields
Test Coverage
tests/test_input_model.py
Added test_input_model_custom_generic_type_import() function to validate that custom generic types are imported using full module paths

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed, breaking-change

Poem

🐰 Generic types now wear their homes with pride,
Module names beside their simple names reside,
CustomDict hops through tests so bright,
With fully qualified imports in sight!
A rabbit's delight in structured types.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: enhancing generic type import handling to use module paths for custom generic types.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

📚 Docs Preview: https://pr-2858.datamodel-code-generator.pages.dev

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/data/python/input_model/pydantic_models.py (1)

16-19: Optional: Simplify generic inheritance.

Inheriting from UserDict[TK, TV] already makes the class generic, so the explicit Generic[TK, TV] is redundant. The preferred form would be:

class CustomGenericDict(UserDict[TK, TV]):
    """Custom generic dict for testing generic type import."""
    pass

However, if you're intentionally testing edge cases with redundant Generic inheritance, this is fine to keep.

🔎 Proposed simplification
-class CustomGenericDict(UserDict[TK, TV], Generic[TK, TV]):
+class CustomGenericDict(UserDict[TK, TV]):
     """Custom generic dict for testing generic type import."""
     
     pass
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86ad441 and 21fa6f4.

📒 Files selected for processing (3)
  • src/datamodel_code_generator/__main__.py
  • tests/data/python/input_model/pydantic_models.py
  • tests/test_input_model.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: Analyze (python)
  • GitHub Check: benchmarks
  • GitHub Check: py312-black22 on Ubuntu
  • GitHub Check: py312-isort6 on Ubuntu
  • GitHub Check: py312-isort7 on Ubuntu
  • GitHub Check: 3.14 on Ubuntu
  • GitHub Check: 3.12 on Windows
  • GitHub Check: py312-isort5 on Ubuntu
  • GitHub Check: 3.12 on Ubuntu
  • GitHub Check: 3.10 on Windows
  • GitHub Check: 3.13 on Windows
  • GitHub Check: py312-black24 on Ubuntu
  • GitHub Check: 3.14 on Windows
  • GitHub Check: 3.11 on Windows
  • GitHub Check: build-deploy
🔇 Additional comments (2)
src/datamodel_code_generator/__main__.py (1)

691-709: LGTM! Clean implementation for module-qualified origin names.

The enhanced logic correctly returns fully qualified names (module.name) for custom generic origins while preserving simple names for standard library types. The safety checks (if module and module not in {...} and if name:) properly handle edge cases, and the fallback logic remains intact.

tests/test_input_model.py (1)

730-742: LGTM! Comprehensive test coverage for custom generic imports.

The test properly validates that custom generic types are imported with their full module paths and used correctly in type annotations. The assertions cover both required and optional field scenarios.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Dec 30, 2025

CodSpeed Performance Report

Merging #2858 will not alter performance

Comparing fix/generic-type-import (21fa6f4) with main (86ad441)

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

Summary

✅ 11 untouched
⏩ 98 skipped1

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 30, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.52%. Comparing base (86ad441) to head (21fa6f4).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2858   +/-   ##
=======================================
  Coverage   99.52%   99.52%           
=======================================
  Files          90       90           
  Lines       14929    14935    +6     
  Branches     1787     1788    +1     
=======================================
+ Hits        14858    14864    +6     
  Misses         38       38           
  Partials       33       33           
Flag Coverage Δ
unittests 99.52% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi merged commit a3cd521 into main Dec 30, 2025
37 checks passed
@koxudaxi koxudaxi deleted the fix/generic-type-import branch December 30, 2025 05:41
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix for the --input-model feature. The change modifies _get_origin_name() to return fully qualified names (module.ClassName) for custom generic types instead of just the class name. Previously, using custom generic types (like CustomGenericDict from a user module) with --input-model would generate code that referenced the type without the necessary import, causing broken output. The fix ensures proper imports are generated. Since the previous behavior was broken (generated non-working code), this is not a breaking change - it's a fix that makes the feature work correctly for custom generics.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jan 1, 2026

🎉 Released in 0.51.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant