[ty] Improve and document equivalence for module-literal types (#19243)

This commit is contained in:
Alex Waygood 2025-07-10 10:11:10 +01:00 committed by GitHub
parent 59aa869724
commit 934aaa23f3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 89 additions and 18 deletions

View file

@ -502,5 +502,55 @@ def f6(a, /): ...
static_assert(not is_equivalent_to(CallableTypeOf[f1], CallableTypeOf[f6]))
```
## Module-literal types
Two "copies" of a single-file module are considered equivalent types, even if the different copies
were originally imported in different first-party modules:
`module.py`:
```py
import typing
```
`main.py`:
```py
import typing
from module import typing as other_typing
from ty_extensions import TypeOf, static_assert, is_equivalent_to
static_assert(is_equivalent_to(TypeOf[typing], TypeOf[other_typing]))
static_assert(is_equivalent_to(TypeOf[typing] | int | str, str | int | TypeOf[other_typing]))
```
We currently do not consider module-literal types to be equivalent if the underlying module is a
package and the different "copies" of the module were originally imported in different modules. This
is because we might consider submodules to be available as attributes on one copy but not on the
other, depending on whether those submodules were explicitly imported in the original importing
module:
`module2.py`:
```py
import importlib
import importlib.abc
```
`main2.py`:
```py
import importlib
from module2 import importlib as other_importlib
from ty_extensions import TypeOf, static_assert, is_equivalent_to
# error: [unresolved-attribute] "Type `<module 'importlib'>` has no attribute `abc`"
reveal_type(importlib.abc) # revealed: Unknown
reveal_type(other_importlib.abc) # revealed: <module 'importlib.abc'>
static_assert(not is_equivalent_to(TypeOf[importlib], TypeOf[other_importlib]))
```
[materializations]: https://typing.python.org/en/latest/spec/glossary.html#term-materialize
[the equivalence relation]: https://typing.python.org/en/latest/spec/glossary.html#term-equivalent