@@ -168,6 +168,33 @@ def dump_all(self, *, multiline: bool = False) -> str:
168168 items = ", " .join (f'"{ name } "' for name in name_list )
169169 return f"__all__ = [{ items } ]"
170170
171+ def get_effective_name (self , from_ : str | None , import_ : str ) -> str :
172+ """Get the effective name after alias resolution."""
173+ return self .alias .get (from_ , {}).get (import_ , import_ )
174+
175+ def remove_unused (self , used_names : set [str ]) -> None :
176+ """Remove imports not referenced in used_names.
177+
178+ Note: Checks both effective name (after alias) and original name to handle
179+ cases where code may reference either form (e.g., type annotations may use
180+ original name while runtime code uses alias).
181+ """
182+ unused = [
183+ (from_ , import_ )
184+ for from_ , imports_ in self .items ()
185+ for import_ in imports_
186+ if not {self .get_effective_name (from_ , import_ ), import_ }.intersection (used_names )
187+ ]
188+ for from_ , import_ in unused :
189+ alias = self .alias .get (from_ , {}).get (import_ )
190+ reference_path = next (
191+ (p for p , i in self .reference_paths .items () if i .from_ == from_ and i .import_ == import_ ),
192+ None ,
193+ )
194+ import_obj = Import (from_ = from_ , import_ = import_ , alias = alias , reference_path = reference_path )
195+ while self .counter .get ((from_ , import_ ), 0 ) > 0 :
196+ self .remove (import_obj )
197+
171198
172199IMPORT_ANNOTATED = Import .from_full_path ("typing.Annotated" )
173200IMPORT_ANY = Import .from_full_path ("typing.Any" )
0 commit comments