## Summary
Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:
```python
def clean(value: str | int) -> str:
value.stirp() # missing-attribute: neither str nor int has stirp
return value.strip() # missing-union-attribute: str has strip, int does not
```
The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.
Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.
### Comparison to other type checkers
Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.
### Compatibility
`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.
Fixesastral-sh/ty#2839 and fixesastral-sh/ty#2471.
## Test Plan
A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).
---------
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
## Summary
Django calls `.encode()` on a union of hundreds of string literals.
Looking up the method produces a bound method for each literal. When
building the union of those methods, ty compared every pair even though
their distinct `__self__` values already distinguish them.
We now skip the subtype and complement checks for methods bound to
distinct singleton literals. `LiteralString` still needs the general
check because it can include a particular literal. Distinct class
objects, distinct module objects, and a dynamic type paired with a
nominal instance other than `object` can also skip the checks.
A cold `ty check` of Django used 3.27% fewer instructions.
---------
Co-authored-by: Charlie Marsh <charliemarsh@openai.com>
## Summary
With this PR, we now support the following scenario where a function on
a class is shadowed by an instance attribute:
```python
class C:
def method(self, x: int) -> str:
return str(x)
def some_compatible_method(self, x: int) -> str:
return str(x)
def swap(self) -> None:
self.method = self.some_compatible_method # previously an error
c = C()
c.swap()
c.method(42) # previously an error (two, actually)
```
(see [this
section](https://github.com/astral-sh/ruff/blob/078b001e5c09f9c301ee7d91092b4946d0591d63/crates/ty_python_semantic/resources/mdtest/call/methods.md#shadowing-methods)
for an in-depth description of what happens here)
Shadowing a method in this way is only sound in a small number of cases.
We deliberately relax conditions here to support various use cases that
came up in the ecosystem. We only require the shadowing callable
(`self.some_compatible_method` above) to be assignable to the
(generalized, regular) callable type of the original `method` after that
has been bound to the receiver in question (`self` here).
See the mdtests linked above for a broaded discussion of the unsoundness
that this introduces. We plan to add a new strict-mode diagnostic for
users who want to prevent those scenarios.
We implement this in the following way:
- When validating the assignment `self.method = ...`, we compare the
right-hand side callable with a "contract type" that is computed from
the bound-method type of the original method, which results in (`(x:
int) -> str`) for the example above. This allows the assignment above to
pass.
- During attribute lookup (`c.method`), we "hide" the implicit instance
attribute (this needs to be done in two places, unfortunately). This
means that `c.method` only sees the original function on the meta type
`C` (and no "fallback" on the instance). And so according to normal
descriptor protocol rules, this means that we simply get a bound method
object (`C.method` bound to `c`). This avoids confusing and problematic
union types that consist of (a) the bound method resulting from binding
the original function to the new receiver and (b) the bound method
referring to the `self` receiver which is stored on the instance. It
might also be a performance optimization.
fixesastral-sh/ty#350.
fixesastral-sh/ty#4823.
## Ecosystem
Looks good. A few exceptions:
- GraphQL-core: I documented this regression in an mdtest. See my inline
comment
- hydra-zen: This is a pre-existing limitation. I reported
https://github.com/astral-sh/ty/issues/4926
## Testing
Updated existing mdtests
Intersection arguments to generic functions can offer several valid
specializations, with relationships between their type variables and
other arguments. Collect these constraints through the full
constraint-set-assignability type relation so inference preserves
variance, alternatives, and correlations. For example, another argument
can select `T = A` from the alternatives provided by `Sink[A] &
Sink[B]`.
There are some cases we have to carve out:
- Constraint-set assignability can currently lose constraints when
gradual types are involved. https://github.com/astral-sh/ruff/pull/28307
will fix this; until then we have to keep gradual types in the old
solver to avoid regression.
- ParamSpec and TypeVarTuple must be kept in the old solver until the
new solver supports them. This includes callables with `ParamSpec` or
`TypeVarTuple` that are nested inside an intersection. We don't handle
this problem in general, but by far the most common case is an
intersection with `~AlwaysTruthy` or `~AlwaysFalsy`. We avoid regression
in that scenario by, whenever we have a single-positive-element
intersection in covariant position, dropping the negative element(s) and
recursing into the positive element in the old solver, instead of
passing the intersection to the new solver. This is a sound upcast, and
negative intersection elements generally don't contribute any
constraints to generics solving.
This depends on #29014 for validating declared upper bounds when an
inferred specialization contains caller-fixed type variables.
This partially addresses astral-sh/ty#3557 and astral-sh/ty#2799.
Argument checking and return inference still use the union-merged
specialization when there are multiple valid solutions, and we haven't
moved unions into the new solver yet.
Fixesastral-sh/ty#3719.
## Ecosystem report
Analyzed head: `77137c770276c0910f4f8fc14bbaa44f233ee82e`. Four false
positives are removed in Tanjun and xarray; Tornado gains a correct
diagnostic under strict generic narrowing. The general
caller-fixed-variable solver limitation also reproduces on main and is
tracked separately in
[ty#4696](https://github.com/astral-sh/ty/issues/4696). [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/28677#issuecomment-5780439815).
## Summary
Consider the following example where we call a method on an object of
type `T: E1 | E2`:
```py
class E1:
def f(self) -> list[Self]:
return [self]
class E2:
def f(self) -> set[Self]:
return {self}
def _[T: E1 | E2](obj: T):
reveal_type(obj.f())
```
How should the `obj.f` attribute access be resolved? We can't bind
`E1.f` to the full `T: E1 | E2` type, since that would invalidate the
implicit `self: Self` annotation of `E1.f`, with `Self: E1`. But we can
use a trick: we can observe that `T = T & (E1 | E2)`. This is true
because `T` is a subtype of `E1 | E2` due to its bound, and so
intersecting `T` with `E1 | E2` just gives us `T`. We can expand that to
get `T = T & E1 | T & E2`. And on the two elements of this union type,
we *can* actually access `E1.f` and `E2.f`, respectively. Accessing `f`
on the first union element `T & E1` gives us `E1.f` as a bound method
with a receiver of `T & E1`, which is accepted by `Self: E1`. After
doing the same for the second union element, we get:
```
(bound method E1.f with receiver T & E1) | (bound method E2.f with receiver T & E2)
```
This means that the result of this call should be `list[T & E1] | set[T
& E2]`. Mypy reveals `list[E1] | set[E2]` here, which seems clearly
wrong. Pyrefly infers the expected intersection types. And Pyright
infers `list[E1*] | set[E2*]` where the stars indicate some
intersection-like connection to the typevar, so this also seems
consistent.
fixes https://github.com/astral-sh/ty/issues/2585
fixes https://github.com/astral-sh/ty/issues/3871
## Ecosystem
Looks good!
*"The two additions are an extra copy of an existing discord.py argument
error and a pre-existing xarray setter error exposed when arithmetic
preserves the receiver type instead of producing `Unknown`."*
## Test Plan
New and updated Markdown tests.
ty did not report a deprecation when applying a decorator selected a
deprecated overload. This missed, for example, the deprecated
`AsyncIterator` annotation on `@asynccontextmanager`.
Report deprecations for overloads selected by function and class
decorator applications. Avoid repeating deprecation warnings for
explicitly referenced functions while retaining warnings for implicitly
invoked callable and constructor methods.
Fixesastral-sh/ty#4620.
## Test plan
Added mdtests for deprecated and non-deprecated overloads on function
and class decorators, dataclass transformers, callable instances, and
constructors. They also cover conditional and stacked decorators,
implicit methods and constructor chains, deprecated implementations,
`no_type_check`, and `asynccontextmanager`.
## Ecosystem report
At PR head
[`7e04af3dcb77c131dbd2865a324df4c69a5810b4`](https://github.com/astral-sh/ruff/commit/7e04af3dcb77c131dbd2865a324df4c69a5810b4),
the ecosystem run found 491 additional `deprecated` warnings across 73
projects: 468 for context-manager decorators and 23 for
pytest-robotframework's `keyword` decorators. The warnings are
consistent with equivalent explicit calls and do not block readiness.
Some messages are misleading when the function's return type is
`Unknown` or an already-annotated `Generator` has a narrower send type.
[Full ecosystem
report](https://github.com/astral-sh/ruff/pull/28999#issuecomment-5897426490)
A method that cannot accept its implicit positional receiver can
currently satisfy a callable contract, including a protocol method or
`Callable[[], int]`, even though calling the bound method fails.
Record an unsatisfiable receiver constraint when binding has no
positional capacity. Homogeneous `*args` continues to accept and
constrain the receiver, and fixed unpacked tuples consume their leading
argument. Regression tests cover protocol and callable assignments,
descriptors, variadics, and overloads. The related method-override
snapshot is updated.
Closesastral-sh/ty#4158.
---------
Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
Co-authored-by: David Peter <mail@david-peter.de>
The method documentation incorrectly described `classmethod` descriptors
as unmodeled and `inspect.getattr_static` as unwrapping `staticmethod`
descriptors. Clarify that static lookup returns the descriptor, while
ordinary attribute access returns a bound class method or the underlying
static method function. Explain why the descriptor's revealed type still
uses the wrapped function's name and signature.
## Test plan
This changes prose only; the existing mdtest examples and expected type
displays are unchanged. Checked the explanations against the
implementation and the descriptor tests in `call/getattr_static.md`.
File-scoped Markdown hooks pass.
## Summary
This PR changes our representation of `BoundMethodType` so that it can
cover more use cases. In particular, we can now retain the full
`BoundMethodType` (including the underlying function and the captured
receiver) for decorated and synthesized callables. For example,
`SomeDataclass.__init__` is now a bound method, instead of just a
function-like callable with an eagerly bound signature.
This allows us to model the behavior of these types more precisely. For
example, we now recognize that they have attributes like `__self__` or
`__func__`. This addresses https://github.com/astral-sh/ty/issues/1452
and leads to some ecosystem improvements like this example from Bokeh:
```py
class Node:
@staticmethod
def visit_html(visitor, node):
...
html = visit_html.__func__ # previously an error
```
Due to the more faithful representation of these types, we now also
start to allow overrides of `classmethods`s with `staticmethods`s, and
instancemethods with `staticmethods`. This is also where the bulk of the
ecosystem changes come from. For example, we now allow the following
pattern, which appears to be rather common in cases where the subclass
doesn't need the `cls` parameter for the implementation (mypy and
pyrefly also allow this; pyright emits a wrong/confusing error):
```py
class Base:
@classmethod
def f(cls, x: int): ...
class Sub(Base):
# previously `invalid-method-override`, now allowed
@staticmethod
def f(x: int): ...
```
closes https://github.com/astral-sh/ty/issues/1452
closes https://github.com/astral-sh/ty/issues/4504
closes https://github.com/astral-sh/ty/issues/4341
also related: https://github.com/astral-sh/ty/issues/4459 (this PR fixes
the error, but need to investigate more)
also related: https://github.com/astral-sh/ty/issues/1172
## Test strategy
Hand-written mdtests (new and updated)
## Summary
We now allow cached classmethods to be accessed through generic classes:
```python
from functools import lru_cache
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
@classmethod
@lru_cache
def make(cls) -> "Box[T]":
return cls()
Box.make() # Previously: invalid-attribute-access.
```
Previously, we recorded `classmethod` and `staticmethod` on the original
function type, but lost that binding information when another decorator
(`lru-cache`) returned a callable object. We now preserve the complete
wrapped callable when constructing these descriptors and use the
existing bound-method representation to bind the class argument. (This
also retains wrapper attributes such as `cache_clear` and
overload-specific return types.)
Closes https://github.com/astral-sh/ty/issues/4431.
A generic subclass with a defaulted type parameter can incorrectly fail
the implicit `__init_subclass__` receiver check. The receiver is
default-specialized while the inherited method's `Self` bound retains
the subclass's type variables, producing a comparison such as
`Child[int]` against `Base[T@Child]`.
Use the subclass's identity specialization for the implicit `cls`
argument so the receiver and inherited hook use the same type
parameters. This accepts valid class definitions while retaining
explicit receiver restrictions and keyword argument validation.
Closesastral-sh/ty#4411.
## Test plan
Added mdtests covering:
- Generic subclass receivers with no defaults, all-default parameters,
and mixed required and defaulted parameters.
- Legacy `TypeVar` defaults and explicit `cls` annotations, including
rejection of incompatible receiver specializations.
- Class keyword arguments, including values typed using a subclass
parameter and rejection of incompatible values.
Reassigning an object inside a loop leaves narrowing of its attributes
or indexed elements in effect from before the loop. This can make a
`while` condition appear permanently true and cause ty to treat
reachable code after the loop as unreachable.
Create loop-header definitions for places invalidated by reassignment,
and include their fallback member types when computing narrowing across
loop-back paths. Preserve narrowing established after reassignment and
the initial narrowing when a reassignment cannot reach another
iteration. Propagate invalidation through nested loop headers with
memoization.
Exclude synthetic loop headers from attribute-assignment discovery:
rebinding a receiver does not write its attributes or initialize `Final`
values. Treat discarded dictionary-key assignments as invalidations so
rejected replacements and property-setter inputs do not become inferred
key values on subsequent iterations.
Fixes https://github.com/astral-sh/ty/issues/4379.
## Ecosystem
The ecosystem run removes 55 false-positive Pydantic errors and one
Pyodide warning. It adds three expected websockets diagnostics by making
a previously unreachable `join` reachable; the existing annotations
allow mixed text and binary fragments. Minimized reproductions confirm
these changes are expected, with no regressions found.
## Test plan
- Extend `while` and `for` mdtests to cover condition, body, and
normal-exit narrowing after object replacement, explicit `continue`,
nested-loop early exits, nested attributes, and subscripts.
- Verify that break-only paths preserve initial narrowing and that
assertions on replacement objects narrow the next iteration.
- Verify method binding before receiver-rebinding loops and at external
calls, and distinguish actual `Final` initialization inside loops from
receiver rebinding.
- Cover accepted and rejected dictionary replacements, narrowing after
rejected replacements, and property setters whose input types differ
from their getters, including loop-carried dictionary values.
## Summary
This is a first step towards #20411. After this, we would work to either
upstream changes or adjust things within Ruff.
Performance improvements have already been upstreamed
(https://github.com/rust-lang/annotate-snippets-rs/pull/437,
https://github.com/rust-lang/annotate-snippets-rs/pull/440)
Re-implemented the following from the fork:
- Hidden snippets
(https://github.com/rust-lang/annotate-snippets-rs/issues/448)
- Renderer-level disabling of hyperlinks
- Jupyter cell indices
(https://github.com/rust-lang/annotate-snippets-rs/issues/449)
- Fixable mark
(https://github.com/rust-lang/annotate-snippets-rs/issues/450)
- `lineno_offset` (maybe not needed if #20648 is taken care of)
- anonymized lines affects origin
(https://github.com/rust-lang/annotate-snippets-rs/issues/451)
- cut indicator (maybe not needed if we can switch to unicode renderer)
Additional hacks to minimize behavior change include
- Adjust upstream's hidden severity behavior to match Ruff's
(https://github.com/rust-lang/annotate-snippets-rs/issues/452)
- How newlines are annotated
(https://github.com/rust-lang/annotate-snippets-rs/issues/454)
- To not indent for line numbers when none will be present
(https://github.com/rust-lang/annotate-snippets-rs/issues/453)
- Enabling `simd` by default
All of the above represents work that needs to be resolved to address
#20411.
`lib.name` hack is used to simplify maintenance with the assumption that
we'll continue working towards #20411.
Behavior changes that were included
- Tweak when implicit padding lines are present
- Fix Origin's line/column is now derived from the primary annotation
- Make consistent the rendering of primary/context annotations
- Fix snippets to show up for empty source (but may degrade #24528)
- Fix handling of term width
- Fix rendering of annotations between newline and first character
(granted, maybe the caller is wrong)
- Tweak multiline annotation markers
New or upcoming features annotate-snippets features that we will be able
to leverage by moving this forward
- `AnnotationKind::Visible` to improve the quality of built-in
code-folding if Ruff were to switch to it
- `DecorStyle::Unicode`
- *(upcoming)* No-graphiscs mode for screen readers (may also be useful
for AIs)
Deferred:
- Moving related `Group`s into the same `Report`
- Using `secondary_title` for any `Group` after the first in a `Report`
- Using a `Snippet`, instead of titles, for "virtual code" like
https://github.com/astral-sh/ruff/pull/27033#discussion_r3622727236
- Switching hidden snippets to `Origin`
## Test Plan
Within cpython, I ran
```console
$ hyperfine -i "../../ruff/target-baseline/release/ruff check" "../../ruff/target-update/release/ruff check" -N -m20 --output=null
Benchmark 1: ../../ruff/target-baseline/release/ruff check
Time (mean ± σ): 27.5 ms ± 1.1 ms [User: 33.0 ms, System: 108.4 ms]
Range (min … max): 25.0 ms … 31.7 ms 94 runs
Warning: Ignoring non-zero exit code.
Benchmark 2: ../../ruff/target-update/release/ruff check
Time (mean ± σ): 28.1 ms ± 2.0 ms [User: 33.4 ms, System: 105.7 ms]
Range (min … max): 24.8 ms … 38.9 ms 102 runs
Warning: Ignoring non-zero exit code.
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use t
he '--warmup' or '--prepare' options.
Summary
../../ruff/target-baseline/release/ruff check ran
1.03 ± 0.08 times faster than ../../ruff/target-update/release/ruff check
```
Before:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/2d94dabf-b28d-48c1-b17c-52aac59fd57e"
/>
After:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/b388ada3-e3d7-4ba0-b90b-1330eb81f4be"
/>
## Summary
Prior to this change, calling an inherited `__new__` implementation
could lose `Self` and return `Unknown`. This caused us to miss invalid
attribute access and broke chains of custom `__new__` implementations:
```py
from typing import Self
class Foo: ...
class Bar(Foo):
def __new__(cls) -> Self:
return Foo.__new__(cls)
class Baz(Bar):
def __new__(cls) -> Self:
result = Bar.__new__(cls) # Previously: Unknown
result.nonexistent() # Previously: no diagnostic
return result
```
This gives every unannotated `__new__` receiver an implicit
`type[Self]`, matching the constructor typing specification and
preserving `Self` through inherited calls.
It also preserves existing generic constructor calls where the synthetic
`cls` receiver would otherwise be specialized and checked twice. The
regression coverage includes overloaded callbacks, signature-preserving
and callable-protocol decorators, `Concatenate`, and aliased receiver
types; the intentionally odd nested and `Concatenate` inference results
remain documented as pre-existing limitations.
Closes https://github.com/astral-sh/ty/issues/3965.
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
## Summary
Prior to this change, we could incorrectly reject a call to a stored
bound method obtained from a class-based protocol. Member lookup has
already specialized the method for its receiver, but calling through a
callable union reconstructed the original signature and prepended the
receiver as a synthetic argument. Generic call inference then
structurally checked the inferred `self` annotation again:
```python
from collections.abc import Iterator
from typing import Any
class PeekIterator(Iterator[Any]):
def __init__(self, iterator: Iterator[Any]) -> None:
self._next = iterator.__next__
def __next__(self) -> Any:
# Before: Expected `Self@__next__`, found `Iterator[Any]`
return self._next()
def use_fallback(self) -> None:
self._next = lambda: None
```
The receiver is already bound, so `Iterator.__next__` genuinely takes no
call-site arguments and should not be checked against `Self` again. We
now consume an implicit positional receiver before call inference, apply
the `typing.Self` substitution to the remaining signature, and refresh
its return type. This removes the false positive and avoids re-entering
recursive protocol interfaces during binding, which could otherwise
cause overloaded recursive members to grow the deferred constraint graph
combinatorially.
This also corrects constructor diagnostics for class-based protocols.
Previously we counted the implicit receiver in both the expected and
supplied arity:
```python
from collections.abc import Hashable
def construct(value: Hashable) -> None:
# Before: expected 1, got 4
# After: expected 0, got 3
type(value)(1970, 1, 1)
```
Because binding removes the leading parameter, we preserve its
source-parameter offset so invalid-argument and missing-argument
diagnostics still point at the correct declaration. Explicit, variadic,
keyword-only, and other nonstandard receivers retain the existing
call-inference path; the protocol relation itself is unchanged.
The independent recursive traversal in `redundant-cast` checks is
handled separately in #26708.
Related: <https://github.com/astral-sh/ty/issues/3954>
## Summary
Split `ty_extensions` into a public part (`ty_extensions`), and an
internal part (`ty_extensions._internal`). For now, move everything to
`_internal`, except for:
- `static_assert`
- `Unknown`
- `AlwaysTruthy`, `AlwaysFalsy`
- `Intersection`, `Not`
- `Top`, `Bottom`
- `JustFloat`, `JustComplex`
- `NamedTupleLike`
## Summary
In https://github.com/astral-sh/ty/issues/1686#issuecomment-4343186815,
we decided the following:
> We discussed this internally and our current plan is to treat
instances of `class Mock(Any): ...` as if they were of type `Mock &
Any`. This would enable the use case here, and still give accurate types
(and things like auto-completion) for actual attributes on `Mock`.
>
> Note that this will mean that we treat `class C(Any): ...` differently
from `class C(SomethingOfTypeAnyOrUnknown): ...`. The latter would still
be a normal class with a dynamic base, i.e. an instance of that class
would not be assignable to arbitrary types.
As such, instances of classes that explicitly inherit from `Any` now
retain their nominal type and precise declared members while remaining
assignable to arbitrary types, including`Final` and `Literal` types:
```python
from typing import Any, final
class Mock(Any):
def method(self) -> int: ...
@final
class FinalClass: ...
value: FinalClass = Mock()
result: int = Mock().method()
```
Closes https://github.com/astral-sh/ty/issues/1686.
## Summary
Prior to this change, when narrowing `klass is Y` for `T: (Y, Z)`, where
`Z` extends `Y`, we incorrectly simplified `type[T] & <class 'Y'>` to
`type[T]`.
Both `Y` and `Z` instances are subtypes of `Y`, but only the class
object `Y` satisfies `klass is Y`. Using instance subtyping for the
exact class object discarded that information, causing `Y` itself to
widen to `type[T]` and `Y()` to be checked against `Z`'s constructor. We
now exclude exact class literals and specialized generic aliases from
that check.
We still retain this behavior when a type variable’s upper bound
normalizes to the exact target class object. This can only happen for a
final class, so that class object is the type variable’s only possible
specialization. (This removed ~10 ecosystem false-positives.)
Closes https://github.com/astral-sh/ty/issues/3074.
## Summary
This follows up on [the post-merge
review](https://github.com/astral-sh/ruff/pull/25626#pullrequestreview-4466748160)
of #25626.
`functools.partial` now preserves the full intersection receiver when
delegating member lookup to its nominal `partial[T]` view. Bound-method
fallback still resets the receiver when lookup switches to the separate
underlying function object; the implementation and regression coverage
now make that distinction explicit.
This also parenthesizes compound bound-method receivers in displayed
types and clarifies and relocates the related intersection receiver
documentation and tests.
## Summary
When looking up an attribute on an intersection, we search each positive
element independently. We previously also used that individual element
as the receiver when binding descriptors and `Self`, which meant we lost
constraints:
```python
def f(value: Intersection[A, B]):
reveal_type(value.method()) # A, previously
reveal_type(value.descriptor) # A, previously
```
This change separates (1) the type whose members are searched from (2)
the receiver used to bind the resulting attribute. We continue searching
each intersection element independently, but bind descriptors and Self
using the full intersection:
```python
def f(value: Intersection[A, B]):
reveal_type(value.method()) # A & B
reveal_type(value.descriptor) # A & B
```
Closes https://github.com/astral-sh/ty/issues/3565.
Closes https://github.com/astral-sh/ty/issues/3600.
## Summary
Add a new lint that detects generic types used without explicit type
parameters in annotations (e.g. `list` instead of `list[int]`).
This is equivalent to mypy's `--disallow-any-generics` and pyright's
`reportMissingTypeArgument`.
Can be enabled via:
```
[rules]
missing-type-argument = "warn"
```
It skips classes where all type parameters have PEP 696 defaults.
This should fix the following issue in ty:
- https://github.com/astral-sh/ty/issues/2442
## Test Plan
Added tests covering stdlib generics, user-defined generics, PEP 696
defaults, dotted names, function signatures, base classes, and variable annotations.
---------
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
## Summary
Ref: https://github.com/astral-sh/ty/issues/2724
Adds an mdtest regression case for:
- `bar = staticmethod(foo)`
- `__call__ = staticmethod(foo)`
The test validates class and instance calls with empty, positional, and
keyword arguments.
## Summary
Another small win in terms of typing conformance. This should fix the
last remaining test in
[`specialtypes_any.py`](https://shark.fish/typing-conformance-report/specialtypes_any.html)
## Ecosystem
The new diagnostics look like true positives (in our current strict
interpretation of LSP checks)
## Test Plan
New Markdown test
## Summary
Just a small quick win that should fix the last remaining conformance
test in
[`specialtypes_none.py`](https://shark.fish/typing-conformance-report/specialtypes_none.html).
`types.FunctionType` has the following overloads for `__get__` to model
accessing functions on a class vs. on an instance:
```py
class FunctionType:
@overload
def __get__(self, instance: None, owner: type, /) -> FunctionType:
"""Return an attribute of instance, which is of type owner."""
@overload
def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ...
```
The `instance: None` sentinel of the descriptor protocol is problematic
when we're actually accessing something on an instance of type `None`.
Here, we simply add a special case to fix this. Also, instead of using
`Type::none(db)` as a sentinel in the Rust code, we now use
`Optional<Type<…>>` such that we can use the Rust `None` if we want to
call `__get__` on a non-instance.
Fixes https://github.com/astral-sh/ty/issues/737
## Ecosystem
Looks good. Some strange-looking new diagnostics because symbols were
inferred as `None` where users did not intend that (but no wrong
behavior of ty).
## Test Plan
Adapted existing tests.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
-->
## Summary
The test I've added illustrates the fix. Copying it here too:
```python
from contextlib import contextmanager
from typing import Iterator
from typing_extensions import Self
class Base:
@classmethod
@contextmanager
def create(cls) -> Iterator[Self]:
yield cls()
class Child(Base): ...
with Base.create() as base:
reveal_type(base) # revealed: Base (after the fix, None before)
with Child.create() as child:
reveal_type(child) # revealed: Child (after the fix, None before)
```
Full disclosure: I've used LLMs for this PR, but the result is
thoroughly reviewed by me before submitting. I'm excited about my first
Rust contribution to Astral tools and will address feedback quickly.
Related to https://github.com/astral-sh/ty/issues/2030, I am working on
a fix for the TypeVar case also reported in that issue (by me)
<!-- What's the purpose of the change? What does it do, and why? -->
## Test Plan
<!-- How was it tested? -->
Updated mdtests
---------
Co-authored-by: Douglas Creager <dcreager@dcreager.net>
## Summary
We already had `CallableTypeKind::ClassMethodLike` to track callables
that behave like `classmethods` (always bind the first argument). This
PR adds the symmetric `CallableTypeKind::StaticMethodLike` for callables
that behave like `staticmethods` (never bind `self`).
Closes https://github.com/astral-sh/ty/issues/2114.
## Summary
We're actually quite good at computing this but the main issue is just
that we compute it at the type-level and so wrap it in `Literal[...]`.
So just special-case the rendering of these to omit `Literal[...]` and
fallback to `...` in cases where the thing we'll show is probably
useless (i.e. `x: str = str`).
Fixes https://github.com/astral-sh/ty/issues/1882
Fixes https://github.com/astral-sh/ty/issues/1787
## Summary
Allow method decorators returning Callables to presumptively propagate
"classmethod-ness" in the same way that they already presumptively
propagate "function-like-ness". We can't actually be sure that this is
the case, based on the decorator's annotations, but (along with other
type checkers) we heuristically assume it to be the case for decorators
applied via decorator syntax.
## Test Plan
Added mdtest.
## Summary
Working on py-fuzzer recently (AKA, a Python project!) reminded me how
cool our "inlay hint goto-definition feature" is. So this PR adds a
bunch more of that!
I also made a couple of other minor changes to type display. For
example, in the playground, this snippet:
```py
def f(): ...
reveal_type(f.__get__)
```
currently leads to this diagnostic:
```
Revealed type: `<method-wrapper `__get__` of `f`>` (revealed-type) [Ln 2, Col 13]
```
But the fact that we have backticks both around the type display and
inside the type display isn't _great_ there. This PR changes it to
```
Revealed type: `<method-wrapper '__get__' of function 'f'>` (revealed-type) [Ln 2, Col 13]
```
which avoids the nested-backticks issue in diagnostics, and is more
similar to our display for various other `Type` variants such as
class-literal types (`<class 'Foo'>`, etc., not ``<class `Foo`>``).
## Test Plan
inlay snapshots added; mdtests updated
Refs https://github.com/astral-sh/ty/issues/544
## Summary
Takes a more incremental approach to PEP 613 type alias support (vs
https://github.com/astral-sh/ruff/pull/20107). Instead of eagerly
inferring the RHS of a PEP 613 type alias as a type expression, infer it
as a value expression, just like we do for implicit type aliases, taking
advantage of the same support for e.g. unions and other type special
forms.
The main reason I'm following this path instead of the one in
https://github.com/astral-sh/ruff/pull/20107 is that we've realized that
people do sometimes use PEP 613 type aliases as values, not just as
types (because they are just a normal runtime assignment, unlike PEP 695
type aliases which create an opaque `TypeAliasType`).
This PR doesn't yet provide full support for recursive type aliases
(they don't panic, but they just fall back to `Unknown` at the recursion
point). This is future work.
## Test Plan
Added mdtests.
Many new ecosystem diagnostics, mostly because we
understand new types in lots of places.
Conformance suite changes are correct.
Performance regression is due to understanding lots of new
types; nothing we do in this PR is inherently expensive.
## Summary
We weren't correctly modeling it as a `staticmethod` in all cases,
leading us to incorrectly infer that the `cls` argument would be bound
if it was accessed on an instance (rather than the class object).
## Test Plan
Added mdtests that fail on `main`. The primer output also looks good!
## Summary
- Type checkers (and type-checker authors) think in terms of types, but
I think most Python users think in terms of values. Rather than saying
that a _type_ `X` "has no attribute `foo`" (which I think sounds strange
to many users), say that "an object of type `X` has no attribute `foo`"
- Special-case certain types so that the diagnostic messages read more
like normal English: rather than saying "Type `<class 'Foo'>` has no
attribute `bar`" or "Object of type `<class 'Foo'>` has no attribute
`bar`", just say "Class `Foo` has no attribute `bar`"
## Test Plan
Mdtests and snapshots updated
## Summary
Simplify and fix the implementation of
`ty_extensions.CallableTypeOf[..]`.
closes https://github.com/astral-sh/ty/issues/1331
## Test Plan
Added regression test.