Skip to content

Respect overwrite_existing_annotations for attributes and globals - #1467

Open
Sanjays2402 wants to merge 1 commit into
Instagram:mainfrom
Sanjays2402:fix/overwrite-existing-attribute-annotations
Open

Respect overwrite_existing_annotations for attributes and globals#1467
Sanjays2402 wants to merge 1 commit into
Instagram:mainfrom
Sanjays2402:fix/overwrite-existing-attribute-annotations

Conversation

@Sanjays2402

Copy link
Copy Markdown

Closes #1159

Summary

ApplyTypeAnnotationsVisitor only overwrote existing annotations on function parameters and returns. An attribute or global that already carries an annotation is an AnnAssign, which the transformer never visited, so overwrite_existing_annotations=True had no effect there — patching class X: x: str with a stub class X: x: int left x: str unchanged.

Adds leave_AnnAssign, which (only when overwriting is requested) looks up the qualified name in the stub's attribute annotations and swaps in the stub annotation, recording it in the annotation counts.

Test Plan

New test_annotate_attributes_with_existing_annotations in libcst/codemod/visitors/tests/test_apply_type_annotations.py covers a class attribute, an attribute with a value, and a module-level global. All three fail without the source change and pass with it; libcst/codemod/ is otherwise unchanged (389 passed, with one pre-existing test_codemod_formatter_error_input failure present on a clean checkout too).

This change was prepared with AI assistance; the regression test was run locally and fails without the fix.

ApplyTypeAnnotationsVisitor only replaced an existing annotation on
function parameters and returns. An attribute or global that was already
annotated (an AnnAssign) was never visited, so a stub annotation could
not overwrite it even with overwrite_existing_annotations=True.

Add leave_AnnAssign, which - only when overwriting is requested - looks
up the qualified name in the stub attribute annotations and swaps in the
stub annotation, recording it in the annotation counts.

Adds regression tests for a class attribute, an attribute with a value,
and a module-level global.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 2, 2026
@Sanjays2402

Copy link
Copy Markdown
Author

Ping — this one's waiting on workflow approval before CI can run. Would appreciate a maintainer enabling the run whenever there's a spare moment. Open to feedback on the approach.

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ApplyTypeAnnotationsVisitor does not respect overwrite_existing_annotations for attributes

1 participant