Skip to content

Conversation

@AlexWaygood
Copy link
Member

Summary

Currently we'll happily let you do this without complaining about it:

__doc__ = 42

But this is unsound! All modules are instances of types.ModuleType, and typeshed states that all types.ModuleType instances have a __doc__ attribute of type str | None. Literal[42] is not assignable to str | None, so we should not permit this.

This PR fixes this soundness hole by falling back to declarations on types.ModuleType when checking assignments in the global scope. Cc. @tekknolagi (cf. #18071 (comment)).

I also fix an issue in this PR where we would incorrectly report a symbol as being unbound if it is declared as global in an inner scope and it is an implicit ModuleType global in the global scope, e.g.

def f():
    global __loader__
    print(__loader__)  # we previously emitted `[unresolved-reference]` here

Test Plan

mdtests added

@AlexWaygood AlexWaygood added bug Something isn't working ty Multi-file analysis & type inference labels May 13, 2025
@AlexWaygood AlexWaygood force-pushed the alex/moduletype-declarations branch from 19efb12 to 538e7da Compare May 13, 2025 19:31
@github-actions
Copy link
Contributor

github-actions bot commented May 13, 2025

mypy_primer results

No ecosystem changes detected ✅

Copy link
Contributor

@carljm carljm left a comment

Choose a reason for hiding this comment

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

Looks good!

@AlexWaygood AlexWaygood requested a review from carljm May 13, 2025 20:29
@AlexWaygood
Copy link
Member Author

(Re-requesting review just for the changes pushed in e9b73f0)

@AlexWaygood AlexWaygood merged commit 65e48cb into main May 13, 2025
34 checks passed
@AlexWaygood AlexWaygood deleted the alex/moduletype-declarations branch May 13, 2025 20:37
Glyphack pushed a commit to Glyphack/ruff that referenced this pull request May 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working ty Multi-file analysis & type inference

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants