[ty] __file__ is always a string inside a Python module (#18071)

## Summary

Understand that `__file__` is always set and a `str` when looked up as
an implicit global from a Python file we are type checking.

## Test Plan

mdtests
This commit is contained in:
Carl Meyer 2025-05-13 08:20:43 -07:00 committed by GitHub
parent 142c1bc760
commit f8890b70c3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 13 additions and 2 deletions

View file

@ -982,12 +982,18 @@ mod implicit_globals {
db: &'db dyn Db,
name: &str,
) -> SymbolAndQualifiers<'db> {
// We special-case `__file__` here because we know that for an internal implicit global
// lookup in a Python module, it is always a string, even though typeshed says `str |
// None`.
if name == "__file__" {
Symbol::bound(KnownClass::Str.to_instance(db)).into()
}
// In general we wouldn't check to see whether a symbol exists on a class before doing the
// `.member()` call on the instance type -- we'd just do the `.member`() call on the instance
// type, since it has the same end result. The reason to only call `.member()` on `ModuleType`
// when absolutely necessary is that this function is used in a very hot path (name resolution
// in `infer.rs`). We use less idiomatic (and much more verbose) code here as a micro-optimisation.
if module_type_symbols(db)
else if module_type_symbols(db)
.iter()
.any(|module_type_member| &**module_type_member == name)
{