mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-09 21:28:04 +00:00
[ty] Improve and document equivalence for module-literal types (#19243)
This commit is contained in:
parent
59aa869724
commit
934aaa23f3
3 changed files with 89 additions and 18 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue