ruff/crates
David Peter c15aa572ff
[ty] Use RHS inferred type for bare Final symbols (#19142)
## Summary

Infer the type of symbols with a `Final` qualifier as their
right-hand-side inferred type:
```py
x: Final = 1
y: Final[int] = 1

def _():
    reveal_type(x)  # previously: Unknown, now: Literal[1]
    reveal_type(y)  # int, same as before
```
Part of https://github.com/astral-sh/ty/issues/158

## Ecosystem analysis

### aiohttp

```diff
aiohttp (https://github.com/aio-libs/aiohttp)
+ error[invalid-argument-type] aiohttp/compression_utils.py:131:54: Argument to bound method `__init__` is incorrect: Expected `ZLibBackendProtocol`, found `<module 'zlib'>`
```

This code [creates a
protocol](a83597fa88/aiohttp/compression_utils.py (L52-L77))
that looks like
```pyi
class ZLibBackendProtocol(Protocol):
    Z_FULL_FLUSH: int
    Z_SYNC_FLUSH: int
    # more fields…
```

It then [tries to
assign](a83597fa88/aiohttp/compression_utils.py (L131))
the module literal `zlib` to that protocol. Howefer, in typeshed, these
`zlib` members are annotated like this:
```pyi
Z_FULL_FLUSH: Final = 3
Z_SYNC_FLUSH: Final = 2
```
With the proposed change here, we now infer these as `Literal[3]` /
`Literal[2]`. Since protocol members have to be assignable both ways
(invariance), we do not consider `zlib` assignable to this protocol
anymore.

That seems rather unfortunate. Not sure who is to blame here? That
`ZLibBackendProtocol` protocol should probably not annotate the members
with `int`, given that `typeshed` doesn't use an explicit annotation
here either? But what should they do instead? Annotate those fields with
`Any`?

Or is it another case where we should consider literal-widening?

FYI @AlexWaygood 

### cloud-init

```diff
cloud-init (https://github.com/canonical/cloud-init)
+ error[invalid-argument-type] tests/unittests/sources/test_smartos.py:575:32: Argument to function `oct` is incorrect: Expected `SupportsIndex`, found `int | float`
+ error[invalid-argument-type] tests/unittests/sources/test_smartos.py:593:32: Argument to function `oct` is incorrect: Expected `SupportsIndex`, found `int | float`
+ error[invalid-argument-type] tests/unittests/sources/test_smartos.py:647:35: Argument to function `oct` is incorrect: Expected `SupportsIndex`, found `int | float`
```

New false positives on expressions like
`oct(os.stat(legacy_script_f)[stat.ST_MODE])`. We now correctly infer
`stat.ST_MODE` as `Literal[1]`, because in typeshed, it is annotated as
`ST_MODE: Final = 0`. `os.stat` returns a `stat_result` which is a tuple
subclass. Accessing it at index 0 should return an `int`, but we
currently return `int | float`, presumably due to missing support for
tuple subclasses (FYI @AlexWaygood):
```pyi
class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]):
```
In terms of `typing.Final`, things are working as expected here.


### pywin-32

Many new false positives similar to:

```diff
pywin32 (https://github.com/mhammond/pywin32)
+ error[invalid-argument-type] Pythonwin/pywin/docking/DockingBar.py:288:55: Argument to function `LoadCursor` is incorrect: Expected `PyResourceId`, found `Literal[32645]`
```

The line in question calls `win32api.LoadCursor(0, win32con.IDC_ARROW)`.
The `win32con.IDC_ARROW` symbol is annotated as [`IDC_ARROW: Final =
32512` in
typeshed](2408c028f4/stubs/pywin32/win32/lib/win32con.pyi (L594)),
but
[`LoadCursor`](2408c028f4/stubs/pywin32/win32/win32api.pyi (L197))
expects a
[`PyResourceId`](2408c028f4/stubs/pywin32/_win32typing.pyi (L1252)),
which is an empty class. So.. this seems like a true positive to me,
unless that typeshed annotation of `IDC_ARROW` is meant to imply that
the type should be `Unknown`/`Any`?

### streamlit

```diff
streamlit (https://github.com/streamlit/streamlit)
+ error[invalid-argument-type] lib/streamlit/string_util.py:163:37: Argument to bound method `translate` is incorrect: Expected `bytes`, found `bytearray`
```

This looks like a true positive? The code calls `inp.translate(None,
TEXTCHARS)`. `inp` is `bytes`, and `TEXTCHARS` is:
```py
TEXTCHARS: Final = bytearray(
    {7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F}
)
```
~~We now infer this as `bytearray`, but `bytes.translate` [expects
`bytes` for its `delete`
parameter](2408c028f4/stdlib/builtins.pyi (L710)).
This seems to work at runtime, so maybe the typeshed annotation is
wrong?~~ (Edit: this is now fixed in typeshed)
```pycon
>>> b"abc".translate(None, bytearray(b"b"))
b'ac'
```

## rotki

```diff
+ error[invalid-return-type] rotkehlchen/chain/ethereum/modules/yearn/decoder.py:412:13: Return type does not match returned value: expected `dict[Unknown, str]`, found `dict[Unknown, Literal["yearn-v1", "yearn-v2"]]`
```

The code in question looks like
```py
    def addresses_to_counterparties(self) -> dict[ChecksumEvmAddress, str]:
        return dict.fromkeys(self.vaults, CPT_BEEFY_FINANCE)
```
where `CPT_BEEFY_FINANCE: Final = 'beefy_finance'. We previously
inferred the value type of the returned `dict` as `Unknown`, and now we
infer it as `Literal["beefy_finance"]`, which does not match the
annotated return type because `dict` is invariant in the value type.

```diff
+ error[invalid-argument-type] rotkehlchen/tests/unit/decoders/test_curve.py:249:9: Argument is incorrect: Expected `int`, found `FVal`
```
There are true positives that were previously silenced through the
`Unknown`.

## Test Plan

New Markdown tests
2025-07-07 13:16:40 +02:00
..
ruff Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_annotate_snippets Update Rust toolchain to 1.88 and MSRV to 1.86 (#19011) 2025-06-28 20:24:00 +02:00
ruff_benchmark [ty] Add a DateType benchmark (#19148) 2025-07-04 21:11:47 +01:00
ruff_cache Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_db Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_dev Avoid reformatting comments in rules reference documentation (#19093) 2025-07-02 17:16:44 +02:00
ruff_diagnostics Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_formatter Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_graph Update Rust toolchain to 1.88 and MSRV to 1.86 (#19011) 2025-06-28 20:24:00 +02:00
ruff_index Update Rust toolchain to 1.88 and MSRV to 1.86 (#19011) 2025-06-28 20:24:00 +02:00
ruff_linter Fix F701 to F707 errors in tests (#19125) 2025-07-04 13:43:18 -05:00
ruff_macros Apply fix availability and applicability when adding to DiagnosticGuard and remove NoqaCode::rule (#18834) 2025-06-24 10:08:36 -04:00
ruff_notebook Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_options_metadata [ty] Document configuration schema (#17950) 2025-05-09 10:47:45 +02:00
ruff_python_ast Make dependency get-size2 truly optional in ruff_python_ast (#19052) 2025-06-30 21:50:59 -05:00
ruff_python_ast_integration_tests [ty] AST garbage collection (#18482) 2025-06-13 08:40:11 -04:00
ruff_python_codegen Fix f-string interpolation escaping (#18882) 2025-06-25 10:04:15 +02:00
ruff_python_formatter Update pre-commit dependencies (#19162) 2025-07-07 04:07:44 +00:00
ruff_python_index Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_python_literal Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_python_parser Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_python_semantic [flake8-pyi] Expand Optional[A] to A | None (PYI016) (#18572) 2025-06-27 15:43:11 +00:00
ruff_python_stdlib Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_python_trivia Treat ty: comments as pragma comments (#18532) 2025-06-07 16:02:43 +02:00
ruff_python_trivia_integration_tests Switch to Rust 2024 edition (#18129) 2025-05-16 13:25:28 +02:00
ruff_server Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_source_file [ty] Add environment variable to dump Salsa memory usage stats (#18928) 2025-06-26 21:27:51 +00:00
ruff_text_size [ty] Add environment variable to dump Salsa memory usage stats (#18928) 2025-06-26 21:27:51 +00:00
ruff_wasm Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ruff_workspace Fix description of the format.skip-magic-trailing-comma example (#19095) 2025-07-03 10:39:59 -04:00
ty [ty] Update docs links (#19092) 2025-07-02 17:34:56 +02:00
ty_ide [ty] Sync vendored typeshed stubs (#19174) 2025-07-07 12:00:09 +02:00
ty_project Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ty_python_semantic [ty] Use RHS inferred type for bare Final symbols (#19142) 2025-07-07 13:16:40 +02:00
ty_server [ty] Initial support for workspace diagnostics (#18939) 2025-07-03 11:04:54 +00:00
ty_test Combine OldDiagnostic and Diagnostic (#19053) 2025-07-03 13:01:09 -04:00
ty_vendored [ty] Sync vendored typeshed stubs (#19174) 2025-07-07 12:00:09 +02:00
ty_wasm [ty] Support LSP go-to with vendored typeshed stubs (#19057) 2025-07-02 07:58:58 -04:00