Skip to content

Conversation

@dcreager
Copy link
Member

This updates our function specialization inference to infer type mappings from parameters that are generic aliases, e.g.:

def f[T](x: list[T]) -> T: ...

reveal_type(f(["a", "b"]))  # revealed: str

Though note that we're still inferring the type of list literals as list[Unknown], so for now we actually need something like the following in our tests:

def _(x: list[str]):
    reveal_type(f(x))  # revealed: str

@dcreager dcreager requested a review from carljm as a code owner May 11, 2025 21:07
@dcreager dcreager added the ty Multi-file analysis & type inference label May 11, 2025
@github-actions
Copy link
Contributor

github-actions bot commented May 11, 2025

mypy_primer results

Changes were detected when running on open source projects
trio (https://github.com/python-trio/trio)
- error[invalid-assignment] src/trio/_core/_tests/test_run.py:2745:9: Object of type `ExceptionGroup[Exception]` is not assignable to `ValueError | ExceptionGroup[ValueError]`
+ error[no-matching-overload] src/trio/_tests/test_testing_raisesgroup.py:394:10: No overload of bound method `__init__` matches arguments
+ error[no-matching-overload] src/trio/_tests/type_tests/raisesgroup.py:98:5: No overload of bound method `__init__` matches arguments
+ error[no-matching-overload] src/trio/_tests/type_tests/raisesgroup.py:103:5: No overload of bound method `__init__` matches arguments
+ error[no-matching-overload] src/trio/_tests/type_tests/raisesgroup.py:119:5: No overload of bound method `__init__` matches arguments
+ error[no-matching-overload] src/trio/_tests/type_tests/raisesgroup.py:121:5: No overload of bound method `__init__` matches arguments
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:92:51: Unused blanket `type: ignore` directive
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:95:49: Unused blanket `type: ignore` directive
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:99:57: Unused blanket `type: ignore` directive
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:102:48: Unused blanket `type: ignore` directive
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:106:67: Unused blanket `type: ignore` directive
- warning[unused-ignore-comment] src/trio/_tests/type_tests/raisesgroup.py:107:69: Unused blanket `type: ignore` directive
- Found 1118 diagnostics
+ Found 1116 diagnostics

porcupine (https://github.com/Akuli/porcupine)
- error[invalid-argument-type] porcupine/pluginloader.py:298:40: Argument to function `_decide_loading_order` is incorrect: Expected `dict[Unknown, set[Unknown]]`, found `dict[PluginInfo, set[PluginInfo]]`
- Found 98 diagnostics
+ Found 97 diagnostics

mkosi (https://github.com/systemd/mkosi)
- error[invalid-argument-type] mkosi/__init__.py:4383:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/__init__.py:4424:9: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/burn.py:41:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/qemu.py:1002:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/qemu.py:1061:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/qemu.py:1090:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/qemu.py:1641:9: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- error[invalid-argument-type] mkosi/sysupdate.py:81:13: Argument to function `run` is incorrect: Expected `Mapping[str, str]`, found `dict[str | Unknown, str | Unknown]`
- Found 326 diagnostics
+ Found 318 diagnostics

Expression (https://github.com/cognitedata/Expression)
- error[invalid-argument-type] expression/collections/map.py:186:24: Argument to function `of_list` is incorrect: Expected `list[tuple[Unknown, Unknown]]`, found `list[tuple[_Key_, _Result]]`
- error[invalid-argument-type] expression/collections/map.py:454:32: Argument to function `of_list` is incorrect: Expected `Block[tuple[Unknown, Unknown]]`, found `Block[tuple[_Key, _Value]]`
- error[invalid-argument-type] expression/extra/result/traversable.py:50:21: Argument to function `traverse` is incorrect: Expected `(Unknown, /) -> Result[Unknown, Unknown]`, found `def identity(value: _A) -> _A`
+ error[invalid-argument-type] expression/extra/result/traversable.py:50:21: Argument to function `traverse` is incorrect: Expected `(Result[_TSource, _TError], /) -> Result[Unknown, Unknown]`, found `def identity(value: _A) -> _A`
- error[no-matching-overload] tests/test_parser.py:243:12: No overload of bound method `starmap` matches arguments
- Found 305 diagnostics
+ Found 302 diagnostics

altair (https://github.com/vega/altair)
- error[invalid-argument-type] tests/vegalite/v5/test_api.py:1708:25: Argument to bound method `delitem` is incorrect: Expected `Mapping[Literal["pandas"], Unknown]`, found `dict[str, ModuleType]`
- error[invalid-argument-type] tests/vegalite/v5/test_api.py:1709:25: Argument to bound method `delitem` is incorrect: Expected `Mapping[Literal["numpy"], Unknown]`, found `dict[str, ModuleType]`
- error[invalid-argument-type] tests/vegalite/v5/test_api.py:1710:25: Argument to bound method `delitem` is incorrect: Expected `Mapping[Literal["pyarrow"], Unknown]`, found `dict[str, ModuleType]`
- Found 1563 diagnostics
+ Found 1560 diagnostics

pytest (https://github.com/pytest-dev/pytest)
- error[invalid-argument-type] testing/io/test_terminalwriter.py:188:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["PY_COLORS"], Literal["1"]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:193:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["PY_COLORS"], Literal["0"]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:198:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["NO_COLOR"], Literal["1"]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:203:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["FORCE_COLOR"], Literal["1"]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:221:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["NO_COLOR"], str]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:222:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["FORCE_COLOR"], str]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:227:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["NO_COLOR"], Literal[""]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/io/test_terminalwriter.py:228:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["FORCE_COLOR"], Literal[""]]`, found `_Environ[str]`
- error[invalid-argument-type] testing/test_config.py:1371:25: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["mytestplugin"], PseudoPlugin]`, found `dict[str, ModuleType]`
- error[invalid-argument-type] testing/test_pathlib.py:319:29: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["pointsback123"], ModuleType]`, found `dict[str, ModuleType]`
- error[invalid-argument-type] testing/test_pluginmanager.py:349:29: Argument to bound method `setitem` is incorrect: Expected `Mapping[Literal["PYTEST_PLUGINS"], Literal["xy123"]]`, found `_Environ[str]`
+ error[invalid-argument-type] testing/test_pytester.py:318:29: Argument to bound method `setitem` is incorrect: Expected `Mapping[str | Unknown, ModuleType]`, found `dict[str, ModuleType]`
+ error[invalid-argument-type] testing/test_pytester.py:329:29: Argument to bound method `setitem` is incorrect: Expected `Mapping[str | Unknown, ModuleType]`, found `dict[str, ModuleType]`
+ error[invalid-argument-type] testing/test_pytester.py:342:33: Argument to bound method `setitem` is incorrect: Expected `Mapping[str | Unknown, ModuleType]`, found `dict[str, ModuleType]`
- Found 938 diagnostics
+ Found 930 diagnostics

hydra-zen (https://github.com/mit-ll-responsible-ai/hydra-zen)
- error[type-assertion-failure] tests/annotations/declarations.py:951:5: Actual type `FullBuilds[Unknown] | StdBuilds[Unknown]` is not the same as asserted type `FullBuilds[@Todo(Support for `typing.TypeAlias`)] | StdBuilds[@Todo(Support for `typing.TypeAlias`)]`
- Found 650 diagnostics
+ Found 649 diagnostics

mypy (https://github.com/python/mypy)
- error[invalid-argument-type] mypy/build.py:3486:26: Argument to function `topsort` is incorrect: Expected `dict[Unknown, set[Unknown]]`, found `dict[AbstractSet[Unknown], set[AbstractSet[Unknown]]]`
+ error[invalid-return-type] mypy/expandtype.py:163:16: Return type does not match returned value: Expected `T`, found `Type`
- error[invalid-argument-type] mypy/join.py:602:56: Argument to bound method `__init__` is incorrect: Expected `set[str]`, found `set[str | Unknown]`
- error[invalid-argument-type] mypy/plugins/singledispatch.py:102:47: Argument to function `get_first_arg` is incorrect: Expected `list[list[Unknown]]`, found `list[list[Type]]`
- error[invalid-argument-type] mypy/plugins/singledispatch.py:131:52: Argument to function `get_first_arg` is incorrect: Expected `list[list[Unknown]]`, found `list[list[Type]]`
+ error[no-matching-overload] mypy/plugins/singledispatch.py:102:17: No overload of function `get_proper_type` matches arguments
+ error[no-matching-overload] mypy/plugins/singledispatch.py:131:22: No overload of function `get_proper_type` matches arguments
- error[invalid-argument-type] mypy/plugins/singledispatch.py:208:30: Argument to function `get_first_arg` is incorrect: Expected `list[list[Unknown]]`, found `list[list[Type]]`
- error[invalid-argument-type] mypy/solve.py:147:58: Argument to function `strongly_connected_components` is incorrect: Expected `dict[Unknown, list[Unknown]]`, found `dict[TypeVarId, list[TypeVarId]]`
+ error[invalid-argument-type] mypy/solve.py:147:58: Argument to function `strongly_connected_components` is incorrect: Expected `dict[Unknown | TypeVarId, list[Unknown | TypeVarId]]`, found `dict[TypeVarId, list[TypeVarId]]`
- error[invalid-argument-type] mypy/solve.py:150:32: Argument to function `topsort` is incorrect: Expected `dict[Unknown, set[Unknown]]`, found `dict[AbstractSet[Unknown], set[AbstractSet[Unknown]]]`
- error[invalid-argument-type] mypy/solve.py:150:51: Argument to function `prepare_sccs` is incorrect: Expected `dict[Unknown, list[Unknown]]`, found `dict[TypeVarId, list[TypeVarId]]`
- Found 3334 diagnostics
+ Found 3330 diagnostics

rotki (https://github.com/rotki/rotki)
- error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:165:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Unknown, Unknown]`
+ error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:165:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Asset, Balance]`
- error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:166:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Unknown, Unknown]`
+ error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:166:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Asset, Balance]`
- error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:182:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Unknown, Unknown]`
+ error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:182:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Asset, Balance]`
- error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:183:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Unknown, Unknown]`
+ error[invalid-argument-type] rotkehlchen/accounting/structures/balance.py:183:13: Argument is incorrect: Expected `defaultdict[Asset, Balance]`, found `dict[Asset, Balance]`
- error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[int | Unknown]`
+ error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[Unknown | int]`
- error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[int | Unknown]`
+ error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[Unknown | int]`
- error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[int | Unknown]`
+ error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[Unknown | int]`
- error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[int | Unknown]`
+ error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[Unknown | int]`
- error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[int | Unknown]`
+ error[invalid-argument-type] rotkehlchen/chain/ethereum/modules/eth2/eth2.py:229:17: Argument to bound method `get_validators_profit` is incorrect: Expected `set[int] | None`, found `None | set[Unknown] | set[int] | set[Unknown | int]`

sympy (https://github.com/sympy/sympy)
- warning[possibly-unbound-attribute] sympy/utilities/codegen.py:700:27: Attribute `label` on type `property | Unknown` is possibly unbound
+ error[unresolved-attribute] sympy/utilities/codegen.py:700:27: Type `property` has no attribute `label`

Comment on lines 50 to 52
// Keep this field private, so that the only way of constructing `NominalInstanceType` instances
// is through the `Type::instance` constructor function.
class: ClassType<'db>,
pub(super) class: ClassType<'db>,
Copy link
Member

Choose a reason for hiding this comment

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

hmm, the comment here says to keep this field private ;)

Copy link
Member Author

Choose a reason for hiding this comment

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

Woof, talk about tunnel vision! I had done this to be able to pattern-match on the field so that I could have a match arm that only applied to nominal instances of generic aliases.

I'll back this out and tweak the match arm — though keeping it that way might become more difficult in the future if/when the match becomes more complex, with fallthroughs being needed.

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh, actually there's another trick we can use here. Let me push it up as a proposal to see what you think

Copy link
Member Author

Choose a reason for hiding this comment

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

Here you go — if we add an unused PhantomData field, we can mark that as private to prevent construction, but still allow read/match access to the class field. wdyt? (If you're 👍 then I'll also remove the class() accessor method in favor of just reading the field, but didn't want to clutter the diff with that yet if you prefer the original)

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, I like the way that it allows for easier pattern-matching while preserving the property that it's only possible to construct NominalInstanceTypes from the Type::instance() method!

Comment on lines 676 to 683
(
Type::NominalInstance(NominalInstanceType {
class: ClassType::Generic(formal_alias),
}),
Type::NominalInstance(NominalInstanceType {
class: ClassType::Generic(actual_alias),
}),
) if formal_alias.origin(self.db) == actual_alias.origin(self.db) => {
Copy link
Member

Choose a reason for hiding this comment

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

what about generic protocol instances? Do we need to add a branch for them as well?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good idea, though I'd like to tackle that as a follow-on PR

Comment on lines 57 to +59
// Keep this field private, so that the only way of constructing `NominalInstanceType` instances
// is through the `Type::instance` constructor function.
class: ClassType<'db>,
_phantom: PhantomData<()>,
Copy link
Member

Choose a reason for hiding this comment

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

oh, that's clever! It's a shame I'm only learning about this trick now -- much of the diff in #17525 came from me making the class field private, and I guess that was unnecessary

dcreager added 3 commits May 12, 2025 10:13
* main:
  disable jemalloc on android (#18033)
  [ty] Fix incorrect type of `src.root` in documentation (#18040)
  [ty] Refine message for why a rule is enabled (#18038)
  [ty] Remove brackets around option names (#18037)
  Update pre-commit dependencies (#18025)
  Update docker/build-push-action action to v6.16.0 (#18030)
  Update docker/login-action action to v3.4.0 (#18031)
  Update taiki-e/install-action digest to 83254c5 (#18022)
  Update cargo-bins/cargo-binstall action to v1.12.4 (#18023)
  Update Rust crate ctrlc to v3.4.7 (#18027)
  Update Rust crate clap to v4.5.38 (#18026)
  Update Rust crate jiff to v0.2.13 (#18029)
  Update Rust crate getrandom to v0.3.3 (#18028)
  Update dependency ruff to v0.11.9 (#18024)
  [`pylint`] add fix safety section (`PLW1514`) (#17932)
  python_stdlib: update for 3.14 (#18014)
  [`ruff`] add fix safety section (`RUF033`) (#17760)
  [`pylint`] add fix safety section (`PLC0414`) (#17802)
* main:
  [ty] Apply function specialization to all overloads (#18020)
  Add comma to panic message (#18048)
  [`flake8-pie`] Mark autofix for `PIE804` as unsafe if the dictionary contains comments (#18046)
  [ty] fix infinite recursion bug in `is_disjoint_from` (#18043)
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.

We adds the parentheses, then we takes the parentheses away again.

(Also, the actual fix here is excellent)

dcreager added 4 commits May 12, 2025 21:54
…eepish

* origin/main:
  [ty] Induct into instances and subclasses when finding and applying generics (#18052)
  [ty] Allow classes to inherit from `type[Any]` or `type[Unknown]` (#18060)
  [ty] Allow a class to inherit from an intersection if the intersection contains a dynamic type and the intersection is not disjoint from `type` (#18055)
  [ty] Narrowing for `hasattr()` (#18053)
  Update reference documentation for `--python-version` (#18056)
  [`flake8-bugbear`] Ignore `B028` if `skip_file_prefixes` is present (#18047)
  [`airflow`] Apply try-catch guard to all AIR3 rules (`AIR3`) (#17887)
  [`pylint`] add fix safety section (`PLW3301`) (#17878)
  Update `--python` to accept paths to executables in virtual environments (#17954)
  [`pylint`] add fix safety section (`PLE4703`) (#17824)
  [`ruff`] Implement a recursive check for `RUF060` (#17976)
  [`flake8-use-pathlib`] `PTH*` suppress diagnostic for all `os.*` functions that have the `dir_fd` parameter (#17968)
  [`refurb`] Mark autofix as safe only for number literals in `FURB116` (#17692)
  [`flake8-simplify`] Fix `SIM905` autofix for `rsplit` creating a reversed list literal (#18045)
  Avoid initializing progress bars early (#18049)
…eepish

* origin/main:
  [ty] Understand homogeneous tuple annotations (#17998)
@dcreager dcreager merged commit 0fb94c0 into main May 13, 2025
35 checks passed
@dcreager dcreager deleted the dcreager/specialize-deepish branch May 13, 2025 02:12
dcreager added a commit that referenced this pull request May 13, 2025
…eep-dish

* origin/main:
  [ty] Infer parameter specializations of generic aliases (#18021)
  [ty] Understand homogeneous tuple annotations (#17998)
  [ty] Induct into instances and subclasses when finding and applying generics (#18052)
  [ty] Allow classes to inherit from `type[Any]` or `type[Unknown]` (#18060)
  [ty] Allow a class to inherit from an intersection if the intersection contains a dynamic type and the intersection is not disjoint from `type` (#18055)
  [ty] Narrowing for `hasattr()` (#18053)
  Update reference documentation for `--python-version` (#18056)
  [`flake8-bugbear`] Ignore `B028` if `skip_file_prefixes` is present (#18047)
  [`airflow`] Apply try-catch guard to all AIR3 rules (`AIR3`) (#17887)
  [`pylint`] add fix safety section (`PLW3301`) (#17878)
  Update `--python` to accept paths to executables in virtual environments (#17954)
  [`pylint`] add fix safety section (`PLE4703`) (#17824)
  [`ruff`] Implement a recursive check for `RUF060` (#17976)
  [`flake8-use-pathlib`] `PTH*` suppress diagnostic for all `os.*` functions that have the `dir_fd` parameter (#17968)
  [`refurb`] Mark autofix as safe only for number literals in `FURB116` (#17692)
  [`flake8-simplify`] Fix `SIM905` autofix for `rsplit` creating a reversed list literal (#18045)
  Avoid initializing progress bars early (#18049)
dcreager added a commit that referenced this pull request May 13, 2025
…c protocols (#18054)

Follows on from (and depends on)
#18021.

This updates our function specialization inference to infer type
mappings from parameters that are generic protocols.

For now, this only works when the argument _explicitly_ implements the
protocol by listing it as a base class. (We end up using exactly the
same logic as for generic classes in #18021.) For this to work with
classes that _implicitly_ implement the protocol, we will have to check
the types of the protocol members (which we are not currently doing), so
that we can infer the specialization of the protocol that the class
implements.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Glyphack pushed a commit to Glyphack/ruff that referenced this pull request May 21, 2025
)

This updates our function specialization inference to infer type
mappings from parameters that are generic aliases, e.g.:

```py
def f[T](x: list[T]) -> T: ...

reveal_type(f(["a", "b"]))  # revealed: str
```

Though note that we're still inferring the type of list literals as
`list[Unknown]`, so for now we actually need something like the
following in our tests:

```py
def _(x: list[str]):
    reveal_type(f(x))  # revealed: str
```
Glyphack pushed a commit to Glyphack/ruff that referenced this pull request May 21, 2025
…c protocols (astral-sh#18054)

Follows on from (and depends on)
astral-sh#18021.

This updates our function specialization inference to infer type
mappings from parameters that are generic protocols.

For now, this only works when the argument _explicitly_ implements the
protocol by listing it as a base class. (We end up using exactly the
same logic as for generic classes in astral-sh#18021.) For this to work with
classes that _implicitly_ implement the protocol, we will have to check
the types of the protocol members (which we are not currently doing), so
that we can infer the specialization of the protocol that the class
implements.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ty Multi-file analysis & type inference

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants