Visitar URL original
Simplify import removal cleanup by koxudaxi · Pull Request #3362 · datamodel-code-generator/datamodel-code-generator · GitHub
Skip to content

Simplify import removal cleanup - #3362

Merged
Koudai Aono (koxudaxi) merged 2 commits into
mainfrom
refactor/imports-remove-cleanup
Jun 13, 2026
Merged

Koudai Aono (koxudaxi) merged 2 commits into
mainfrom
refactor/imports-remove-cleanup

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

No description provided.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors the Imports.remove() method to make its deletion logic more explicit. The method now clearly computes whether an import is "dotted," uses that condition to gate removal from storage, and restructures alias cleanup to only delete entries when the mapping exists, while preserving the reference-count semantics that drive all deletions.

Changes

Import Removal Logic Refactoring

Layer / File(s) Summary
Refactor Imports.remove() for explicit dotted imports and alias cleanup
src/datamodel_code_generator/imports.py
The Imports.remove() method now explicitly computes is_dotted_import and uses it to gate removal from self[module] storage. Alias cleanup logic is restructured into a clearer conditional path that only deletes alias entries when the alias mapping exists for the relevant module/name, while maintaining reference-count-driven deletion.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 An import's tale grows neat and tidy,
With dotted checks and alias chicanery—
No magic here, just clearer paths,
Where removal knows its dotted math,
And cleanup flows in honest ways. 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Simplify import removal cleanup' directly describes the main change: refactoring the import removal logic to be clearer and more explicit.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/imports-remove-cleanup

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/datamodel_code_generator/imports.py (1)

106-109: ⚡ Quick win

Consider making storage removal symmetric for both import types.

The condition not is_dotted_import or (key[0] in self and key[1] in self[key[0]]) creates asymmetry: non-dotted imports are removed without checking existence, while dotted imports check first. This is inconsistent with the alias cleanup logic (lines 110-113) which checks existence regardless of import type.

For defensive programming and clarity, consider simplifying to:

if key[0] in self and key[1] in self[key[0]]:
    self[key[0]].remove(key[1])
    if not self[key[0]]:
        del self[key[0]]

This would:

  • Make behavior symmetric and predictable
  • Align with the explicit existence checks in alias cleanup
  • Prevent KeyError if storage state becomes inconsistent
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/datamodel_code_generator/imports.py` around lines 106 - 109, The removal
logic using `if not is_dotted_import or (key[0] in self and key[1] in
self[key[0]]):` is asymmetric and can raise KeyError; change it to always check
membership before removing so both dotted and non-dotted imports follow the same
defensive pattern as the alias cleanup (lines handling alias removals).
Specifically, in the method where `key`, `is_dotted_import`, and `self` are used
to remove stored imports, replace the conditional with a membership check that
ensures `key[0] in self` and `key[1] in self[key[0]]` before calling
`self[key[0]].remove(key[1])` and deleting the empty container.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/datamodel_code_generator/imports.py`:
- Around line 106-109: The removal logic using `if not is_dotted_import or
(key[0] in self and key[1] in self[key[0]]):` is asymmetric and can raise
KeyError; change it to always check membership before removing so both dotted
and non-dotted imports follow the same defensive pattern as the alias cleanup
(lines handling alias removals). Specifically, in the method where `key`,
`is_dotted_import`, and `self` are used to remove stored imports, replace the
conditional with a membership check that ensures `key[0] in self` and `key[1] in
self[key[0]]` before calling `self[key[0]].remove(key[1])` and deleting the
empty container.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 23fc65c9-d0b8-4f1a-9094-4d5d8060e662

📥 Commits

Reviewing files that changed from the base of the PR and between 6192212 and b7de15e.

📒 Files selected for processing (1)
  • src/datamodel_code_generator/imports.py

@koxudaxi
Koudai Aono (koxudaxi) enabled auto-merge (squash) June 12, 2026 14:20
@codspeed

codspeed Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ 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.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing refactor/imports-remove-cleanup (98e9d01) with main (6bd7924)

Open in CodSpeed

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. ↩

@github-actions

Copy link
Copy Markdown
Contributor

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

@koxudaxi
Koudai Aono (koxudaxi) merged commit 615c485 into main Jun 13, 2026
49 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the refactor/imports-remove-cleanup branch June 13, 2026 00:45
@codecov

codecov Bot commented Jun 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (6bd7924) to head (98e9d01).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3362   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          129       129           
  Lines        28829     28826    -3     
  Branches      3484      3482    -2     
=========================================
- Hits         28829     28826    -3     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

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

☔ View full report in Codecov by Harness.
📢 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.

@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: PR #3362 "Simplify import removal cleanup" is an internal refactoring of the unused-import removal logic. The affected code (Imports.remove_unused in imports.py, and the private methods _finalize_modules / _collect_used_names_from_models in parser/base.py) is internal implementation — underscore-prefixed private methods not exported in the public init.py and not exposed as CLI options. There are no changes to command-line options, the public Python API, default values, Python version support, error handling, or Jinja2 templates. The only theoretical breaking vector would be Code Generation Changes, but the PR is a behavior-preserving simplification with no evidence of altered output, and per the ground rules a change cannot be reported as breaking without appearing as such in the diff. Note: I was unable to read the prepared diff/context/deleted-lines files — they reside outside the allowed working directory and every access path (Read tool, bash cat/cp/ln, python, git fetch) was blocked by sandbox/permission policy, and the merge commit 615c485 is a parent-less root commit in this shallow clone so git could not reproduce the diff. This determination is therefore based on the merged source state plus the PR's commit message, which indicate an internal cleanup refactor with no public API/CLI/behavior surface.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.64.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