## Summary
Fixesastral-sh/ty#5035.
When targeting Python 3.12 or earlier, infer covariance for read-only
fields on Pydantic models frozen through a class keyword or
`ConfigDict`. Use the same setter lookup as assignment checking so a
custom `__setattr__` keeps the model invariant. On Python 3.13 and
later, the synthesized `__replace__` still makes these models invariant.
A class that defines `__eq__` and omits `__hash__` gets `__hash__ =
None` at class creation. ty previously found `object.__hash__` instead
and accepted instances of the class and its subclasses where `Hashable`
was required.
Account for the implicit `None` during class-member lookup. Subclasses
inherit it and can restore hashing by defining `__hash__`. Explicit and
generated hashes take precedence, including hashes supplied by frozen
dataclasses and Pydantic models. An equality protocol's own implicit
`None` also stays separate from the hash requirements it imposes on
structural implementations.
Fixes https://github.com/astral-sh/ty/issues/4941.
## Test plan
Compared ty with CPython on the issue reproducer. Python raised
`TypeError` for the equality-only class and its subclass, and accepted
the subclass that restored hashing. ty now rejects the same two
instances for a `Hashable` parameter.
Checked Pydantic 2.13.4 at runtime with frozen models that define
equality and with a base that provides a custom hash. Pydantic generated
hashes for the frozen models, preserved the inherited custom hash when
equality was inherited, and left `__hash__ = None` on the subclass that
redefined equality over the custom hash.
## Ecosystem report
The public run for
[`ac783ae`](https://github.com/astral-sh/ruff/commit/ac783ae505378aa9b46acd4e082f0edf6f5e678c)
found 23 stable diagnostic changes across five projects. We accept three
JAX false positives for this fix. ty loses the relationship between a
mask and the callable selected for its type. The other 20 changes follow
from recognizing equality-only classes as unhashable, including
corrected indexing overloads in static-frame and a missing hash
declaration in pandas-stubs. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/30145#issuecomment-6700457278)
## Summary
Support looking up e.g. `strict=True` in `Annotated` metadata through
PEP 695 aliases, e.g.:
```py
type MyStrictInt = Annotated[int, Strict()]
class Model(BaseModel):
field: MyStrictInt # should be recognized as being strict
```
fixes https://github.com/astral-sh/ty/issues/4980
## Test Plan
New Markdown tests
ty rejected `partial(decorator, option=value)` when the decorator
accepted and returned `Callable[P, str]`. It reported that `P.args` was
incompatible with itself. With this change, binding the option leaves
the decorator free to capture the decorated function’s signature.
The solver tracked `P.args` and `P.kwargs` separately and could overlook
the dependency on `P` when removing the decorator’s local type variables
from a constraint. Record that dependency explicitly. For a specialized
return-type alias, visit the arguments that affect the alias’s value so
the solver can substitute the caller’s parameter list there too.
Fixes astral-sh/ty#4973.
## Test plan
Bisected the reported example to #29543 and checked the fix against the
same example. ty now infers `(name: str) -> str` for the decorated
function. I also compared the semantic mdtests under eight alternate
constraint orderings with the base revision. Each ordering produced the
same failing assertions and diagnostics on both revisions.
## Ecosystem report
At `a3e66405a2b5c4b9062803edbed4ddd45ab2c074`, all seven diagnostic
changes were expected. Five Normal and Uniform property assertions and
two Binomial property assertions now infer the one-dimensional arrays
specified by scipy-stubs, with the correct dtypes. The ecosystem
comparison is clear for review. [Full
report](https://github.com/astral-sh/ruff/pull/30150#issuecomment-6702172316)
Rename the method, attribute, property, and mutable override rules to
`incompatible-…-override`. The old names remain aliases in configuration
and inline suppressions:
| Before | After |
|---|---|
| `invalid-method-override` | `incompatible-method-override` |
| `invalid-attribute-override` | `incompatible-attribute-override` |
| `invalid-property-type-override` | `incompatible-property-override` |
| `invalid-mutable-override` | `incompatible-mutable-override` |
A follow-up PR will split `invalid-method-override` into two rules.
Fixesastral-sh/ty#2001.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
## 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
Respect the `extra` configuration on Pydantic `BaseSettings` models,
including when set through `SettingsConfigDict`. This allows extra
constructor arguments when `extra="allow"` and warns about discarded
arguments when `extra="ignore"`, while continuing to reject them when
`extra="forbid"`.
Closes https://github.com/astral-sh/ty/issues/4865.
## Test Plan
Added Markdown regression tests.
## Summary
This PR adds support for `ForeignKey` and `OneToOneField` used as
primary keys. The `.pk` attribute now has the value type of the related
model's primary key, rather than the related model's type. An explicit
`to_field` selects that field's value type instead.
Example:
```py
from django.db import models
class Book(models.Model):
id = models.UUIDField(primary_key=True)
class Ebook(models.Model):
book = models.OneToOneField(Book, on_delete=models.CASCADE, primary_key=True)
def _(ebook: Ebook):
reveal_type(ebook.book) # Book
reveal_type(ebook.book_id) # UUID
reveal_type(ebook.pk) # UUID (previously Book)
```
closes https://github.com/astral-sh/ty/issues/4847.
## Summary
When a Pydantic model used a quoted annotation, ty ignored its `Field`
metadata. In this example, Pydantic accepts `Model(y=1)`, but ty
reported a missing argument for `x`.
```python
from typing import Annotated
from pydantic import BaseModel, Field
class Model(BaseModel):
x: "Annotated[int, Field(alias='y')]"
Model(y=1)
```
We now read the metadata inside the quoted annotation using the scope
where the field was defined. This also preserves metadata when the
quoted annotation names a type alias.
Closes https://github.com/astral-sh/ty/issues/4868.
Use `# ok` as the marker for mdtest statements whose expectation is that
no diagnostic is emitted. Update the guidance in `AGENTS.md` and replace
existing `# no diagnostic` comments in Ruff and ty mdtests.
## Summary
Suppress `invalid-override` errors for Django models' `Meta`
configurations, similar to mypy and pyrefly, which also seem to make an
exception for these cases.
## Test Plan
Updated existing Markdown tests
## Summary
Django does not add an automatic primary key to abstract models. Skip
synthesizing one when the model declares `abstract = True`.
closes https://github.com/astral-sh/ty/issues/4822.
## Test Plan
New Markdown tests
## Summary
This PR adds support for the `<field>_id` attributes that Django
generates for foreign keys. Their types follow the related model's
primary key, or the field specified by `to_field`.
Example:
```py
from django.db import models
class Author(models.Model):
pass
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def _(book: Book):
reveal_type(book.author) # Author
reveal_type(book.author_id) # int
```
Towards https://github.com/astral-sh/ty/issues/1018.
## Test Plan
New Markdown tests. I checked against Django runtime behavior.
## Summary
This PR adds support for the `get_next_by_<field>()` and
`get_previous_by_<field>()` methods that Django generates for
(non-`null=True`) `DateField` and `DateTimeField` fields.
Example:
```py
from django.db import models
class Article(models.Model):
published = models.DateField()
def _(article: Article):
reveal_type(article.get_next_by_published()) # Article
reveal_type(article.get_previous_by_published()) # Article
```
Towards https://github.com/astral-sh/ty/issues/1018.
## Test Plan
New Markdown tests.
## Summary
This PR adds support for the `get_<field>_display()` methods that Django
generates for model fields with `choices`.
Example:
```py
from django.db import models
class Article(models.Model):
status = models.CharField(
max_length=1,
choices=[("D", "Draft"), ("P", "Published")],
)
article = Article(status="P")
reveal_type(article.status) # str
reveal_type(article.get_status_display()) # str ("Published" at runtime)
```
Towards https://github.com/astral-sh/ty/issues/1018.
## Test Plan
New Markdown test.
## Summary
This PR adds basic tests for Django support in ty, and adds a first
customization point where we now synthesize `.id` and `.pk` attributes
for primary keys on Django models. Django support currently relies on
`django-types`, a fork of `django-stubs` which requires less
special-casing in type checkers.
Example
```py
from django.db import models
class Book(models.Model):
isbn = models.CharField(max_length=13, primary_key=True)
title = models.CharField()
pages = models.IntegerField(null=True)
def _(book: Book):
reveal_type(book.isbn) # str
reveal_type(book.title) # str
reveal_type(book.pages) # int | None (because null=True)
reveal_type(book.pk) # str (because `isbn` is the primary key)
book.id # error: no automatic `id` with a custom primary key
```
## Test Plan
I wrote new Markdown test and also verified all of our assertions
against Django's runtime behavior.
## Summary
Add support for frozen Pydantic fields.
The previous diagnostics was limited to frozen models and did not
support individually frozen fields.
```python
from pydantic import BaseModel, Field
class Model(BaseModel):
x: int = Field(frozen=True)
m = Model(x=1)
# Old
m.x = 5 # No diagnostic
# New
m.x = 5 # error: [invalid-assignment]
```
## Test Plan
New mdtests
The gradual range `T <: Any` does not imply the static range `T <: int`,
as `Any` permits materializations that `int` does not satisfy. We
currently assume this implication in the sequent map, as our
transitivity checks use assignability instead of subtyping. However,
this permits unsound simplifications which can lead to incorrect
inference results.
## Summary
Closes https://github.com/astral-sh/ty/issues/1738
(While this PR also resolves the error in the code provided in
https://github.com/astral-sh/ty/issues/1846, I consider the broader
issue under discussion to still be unresolved)
To fully support implicit type aliases, this PR introduces `Recursive`
types. These represent *structural recursive types*. In other words,
they are anonymous recursive types implicitly constructed through type
inference, rather than a nominally defined recursive type like PEP 695
recursive type aliases.
This is what was being discussed in
https://github.com/astral-sh/ruff/pull/24252#issuecomment-4172655350. We
are not introducing recursive types solely for implicit type aliases;
this is the first step toward completely replacing the current
`Divergent`-based approximate recursive type inference with a full
implementation.
Initially, I planned to completely remove the `Divergent` type alongside
the introduction of `Recursive` types, but because the scope of the
impact was far too large, I decided to replace it incrementally. Both
will coexist until the replacement is complete, but eventually,
everything should be replaced by `Recursive` types.
Following this PR, I plan to use the newly introduced `Recursive` types
to replace various forms of recursive type inference.
## Design
Currently, we approximate and treat recursive type structures generated
by recursive type inference as gradual types containing `Divergent`. For
example, a subscript on `x: Divergent` results in `x[n]: Divergent`.
Consequently, we get:
```
x: list[Divergent]
x[n]: Divergent
x[n][n]: Divergent
```
As a result, the type after subscripting loses the information that `x`
was a recursive list type. We solve this problem by introducing
recursive types.
`RecursiveType` is a binder for a body type that contains a recursive
variable. In other words, it roughly has the following structure:
```rust
struct RecursiveType<'db> {
id: salsa::Id,
body: Type<'db>,
arguments: Option<Specialization<'db>>,
}
struct RecursiveVar<'db> {
id: salsa::Id,
arguments: Option<Specialization<'db>>,
}
enum Type<'db> {
Recursive(RecursiveType<'db>),
RecursiveVar(RecursiveVar<'db>),
...
}
```
For example, for the following implicit type alias:
```python
Tree = tuple[T, "Tree[list[T]] | None"]
# = μF. λT. tuple[T, F[list[T]] | None]
```
the constructed `RecursiveType` looks like this:
```rust
RecursiveType {
id,
body: tuple[T, RecursiveVar { id, arguments: [list[T]] } | None],
arguments: [T]
}
```
Unlike `Divergent`, the recursive variable `RecursiveVar` has no type
properties on its own. Attempting to access this variable immediately
unfolds the recursive type, so questioning the typing properties of the
variable itself is meaningless. Therefore, if any type operation on
`RecursiveVar` appears, it should be a bug.
To infer the container subscript `x[1]` for `x: Tree[int]`, first unfold
`x`'s type. Unfolding replaces references to the recursive binder with
the recursive type itself. Writing `B[a := R]` for capture-avoiding
substitution of `R` for `a` in `B`:
```text
unfold(μa. B) = B[a := μa. B]
```
For `Tree[int]`, substitute the constructor for `F`, then apply `T :=
int`:
```text
unfold((μF. λT. tuple[T, F[list[T]] | None])[int])
= tuple[int, (μF. λT. tuple[T, F[list[T]] | None])[list[int]] | None]
(= tuple[int, Tree[list[int]] | None])
```
Tuple subscripting then selects the element at index 1: `x[1]:
Tree[list[int]] | None`.
## Test Plan
mdtest updated
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
This PR makes a rather large change to how we represent the individual
constraints in a constraint set.
Before, we had a single `Constraint` struct, and assumed that every
individual constraint was a single _range constraint_, which provided a
lower and upper bound for a typevar. Several open workstreams want to
add new kinds of individual constraint. (@ibraheemdev is adding a new
constraint that checks certain gradual bounds; @dcreager is adding a new
constraint that models existentials moar better; @dhruvmanila might need
a new constraint for `ParamSpec`s.)
So, in anticipation of that work, we go ahead and break `Constraint`
apart into an enum, that we can add new variants to in the future. While
we're here, we also move it into a separate submodule to tame the
runaway growth of `constraints.rs`.
We are not adding a single-variant enum. Instead, we have added separate
variants for the different kinds of range constraint that can appear.
Most important, we've broken it apart into separate variants for
only-lower-bound, only-upper-bound, and equivalence bound. That lets us
treat equivalences as a first-class concept, since those are important
to track e.g. for handling the declared constraints of a constrained
typevar. And it gives us an efficiency game in some places, where we had
O(L) lower bounds and O(U) upper bounds, and were having to calculate
O(L×U) different derived sequents from all combinations of those bounds.
We also add separate variants for a "typevar constraint", where one
typevar is being compared directly to another. (So, `T ≤ U`, but not `T
≤ list[U]`.) Those were special-cased in a couple of places, and most
importantly, had an internal representation in `ConstraintSetBuilder`
that was hard to make deterministic. The new representation makes it
easier to identify those special cases, and comes with a deterministic
ordering for free (at least for typevar _range_ constraints).
Given those preliminaries, we also update `SequentMap` so that we
calculate derived sequents globally, outside of any particular
`ConstraintSetBuilder`, and salsa-cache them. That gives us a
performance for certain ecosystem projects, which repeatedly make
comparisons involving complex protocols and `TypedDict` aliases. (Those
are expensive to analyze, and this lets us do that once globally and
share the results across all constraint set solves that use them.)
## Summary
Accept field assignments on Pydantic subclasses that override
`frozen=True` with `frozen=False`.
closes https://github.com/astral-sh/ty/issues/4513.
## Test Plan
Regression tests
## Summary
Skip `Generic[T]` bases when discovering Pydantic model configuration so
legacy generic classes preserve inherited settings.
closes https://github.com/astral-sh/ty/issues/4483
## Test plan
Regression tests
## Summary
Previously, we rejected enum members passed to Pydantic string and
integer fields, even though Pydantic accepts them in lax mode:
```python
from enum import Enum
from pydantic import BaseModel
class Color(Enum):
RED = "red"
class Number(Enum):
SEVEN = 7
class Model(BaseModel):
name: str
count: int
Model(name=Color.RED, count=Number.SEVEN)
Model(name=Number.SEVEN, count=Number.SEVEN)
```
We now include `Enum` in the accepted input types for both lax string
and integer fields. Strict models and strict fields continue to reject
ordinary enum members, while fields that opt out of model-wide
strictness accept them.
Closes https://github.com/astral-sh/ty/issues/4259.
## Summary
When matching a class object against a protocol, we previously treated
any `property` descriptor as an unconditional match for a protocol
property. This reduced compatibility to a name-only check even though
accessing an instance property on the class exposes the descriptor, not
the value returned by its getter:
```py
class HasValue(Protocol):
@property
def value(self) -> str: ...
class Value:
@property
def value(self) -> str: ...
target: HasValue = Value # error
```
This removes the stale shortcut so the class attribute and protocol
member are compared using the normal type relation.
That shortcut also interfered with generic inference for unions, like in
NumPy's `_DTypeLike[T]`, where it allowed a scalar class such as
`np.int64` to match `_SupportsDType[dtype[T]]` without constraining `T`,
overriding the useful `type[T]` match and producing `Unknown`. With
normal property compatibility, the class-object branch binds `T`, so
explicit dtypes remain specialized through downstream calls:
```py
values = np.array([0, 1, 2], dtype=np.int64)
reveal_type(values) # ndarray[..., dtype[signedinteger[_64Bit]]]
reveal_type(np.interp(values, values, values)) # ndarray[..., dtype[float64]]
```
Closes https://github.com/astral-sh/ty/issues/3199.
## Summary
Recognize `pydantic` as being third-party code, and therefore activate
special Pydantic support, even if the package appears in `extra-paths`.
Fixes https://github.com/astral-sh/ty/issues/4159.
## Test plan
Added a regression test
## Summary
Fixesastral-sh/ty#4095.
Synthesize Python 3.13+ `__replace__` methods for Pydantic models while
preserving their dedicated field handling. Exclude private and internal
Pydantic attributes and use model field names rather than constructor
aliases for replacements. Include the synthesized method in class and
instance member discovery without exposing dataclass-only attributes.
Update the existing pinned Pydantic mdtest suite and its lockfile from
Python 3.12 to Python 3.13, where `__replace__` was added.
## Test plan
Add real-Pydantic mdtests for frozen and mutable models, private
attributes, field aliases, inherited and generic fields, `RootModel`,
and `BaseSettings`. Verify direct `__replace__` calls, `copy.replace`,
concrete and generic return types, invalid replacement arguments, and
class/instance completion. Add ordinary base-class and metaclass
`dataclass_transform` replacement mdtests and verify replacement is not
synthesized before Python 3.13.
## Summary
For lax-mode models, we try to model Pydantic's coercion behavior by
promoting some types like `int` to `LaxInt = int | str | ...`. When a
field referred to a non-builtin type, we previously widened the
corresponding constructor parameter type to `Any`, since we didn't know
what that field would accept. However, there is one case where we can be
more strict: if the field refers to another Pydantic model, we can widen
`Child` to `Child | Mapping[str, Any]`, since that represents all
possible values that Pydantic can accept for a field like this:
```py
class Child(BaseModel):
value: int
class Stranger(BaseModel): ...
class Parent(BaseModel):
child: Child
Parent(child=Child(value=1))
Parent(child=Stranger()) # previously accepted, now an error
```
Adding support for this also required proper modeling of a few other
behaviors, or otherwise this would have caused false positives:
- Detecting the [`from_attributes`
setting](https://pydantic.dev/docs/validation/dev/api/pydantic/config/#pydantic.config.ConfigDict.from_attributes).
Models that use this setting still use `Any` as the input type.
- Detecting ["before"
validators](https://pydantic.dev/docs/validation/latest/concepts/validators/#field-before-validator)
which can change the input type. For now, affected fields also still use
`Any` as the input type.
- Handling generic models. `Box[int]` can accept a `Box[str]`, so we
currently use the `Unknown` specialization `Box[Unknown]` for the input
type.
closes https://github.com/astral-sh/ty/issues/3947
closes https://github.com/astral-sh/ty/issues/3510
## Test Plan
- New Markdown tests
- validated all new test assertions against Pydantic runtime behavior
## Ecosystem
The new hits on Prefect are all expected.
## Summary
Copy the underscore-prefixed parameters like `_secrets_dir` from
`BaseSettings.__init__` when synthesizing constructors Pydantic models
derived from for `BaseSettings`. This allows us to type check valid code
like this without any errors:
```py
class Settings(BaseSettings):
host: str
port: int
Settings(_secrets_dir="./secrets")
```
closes https://github.com/astral-sh/ty/issues/4067
## Test plan
New Markdown test
## Summary
The bug: ty treats a Pydantic model field as a required constructor
argument (`missing-argument`) when its default comes from a `Field(...)`
that lives inside a generic `Annotated` type alias. For example:
```py
from typing import Annotated, TypeVar
from pydantic import BaseModel, Field
T = TypeVar("T")
MyField = Annotated[T, Field(default=0)]
class M(BaseModel):
value: MyField[int]
M() # before this change: error[missing-argument] for `value`
```
At runtime pydantic makes `value` optional (it defaults to 0), so the
error is a false positive.
> AI assistance disclosure: I used AI to both draft the PR and the
changes, while acknowledging your AI policy by carefully auditing the
produced PR and changes. I understand them on a very narrow scoped basis
(extending with the Subscript expression). Ofcourse I will reply to any
comments on the PR myself, according to the policy.
I want to be careful about whether this really belongs in ty, so I
checked pydantic's runtime behavior and cross checked two other type
checkers. Pydantic makes the field optional at runtime, so pydantic is
doing the right thing and there is nothing to fix on that side. ty
already honors this default for the inline and bare alias forms (added
in #26650); the only case it misses is the subscripted generic alias,
which pydantic treats exactly the same as the others. So to me this
reads as an internal gap in ty's existing pydantic handling, not new
behavior.
The fix: in `FieldMetadata::collect_from_annotation`, the code that
follows an alias back to its definition only ran when the annotation was
a plain name (like `field: StrictInt`). A subscripted generic alias
(`field: MyField[int]`) is an `Expr::Subscript`, so the function bailed
out early and the default was lost. This change also handles
`Expr::Subscript`: it takes the base name from `subscript.value` and
then follows the alias the same way the plain name case already does.
There is no existing issue for this at the ty repo, if thats the
preferred way, I'll gladly open an issue and link it here.
Scope: the metadata gets collected with the enclosing model's
specialization rather than the alias's own subscript argument. From what
I can tell that does not matter in practice, because a `Field` default
is a runtime value, so its type cannot carry the alias's type variable,
and I checked that a generic model using the alias still behaves
correctly. There is a bigger direction hinted at in the existing comment
and in astral-sh/ty#504 (keep the `Annotated` metadata through
specialization instead of re-parsing the alias definition), but that is
past what I understand and felt out of scope for this bug.
## Test Plan
- Added a regression test to `resources/mdtest/external/pydantic.md`
(`ModelWithGenericAliasField`).
- Checked that it fails before the change (unexpected `missing-argument`
for `value`) and passes after, run with `MDTEST_EXTERNAL=1` so real
pydantic gets installed.
- Ran a standalone repro through a locally built `ty` CLI, including a
generic model variant. It went from `missing-argument` to clean.
- Confirmed on pydantic 2.13.4 that all three forms above are optional
at runtime, and that pyright and mypy (with the pydantic plugin)
currently report all three as required.
- Ran the pre-PR checks locally and they all pass: `cargo clippy
--workspace --all-targets --all-features -- -D warnings` is clean, the
full `cargo test --workspace` passes with 0 failures (whole ruff plus ty
suite), the external regression mdtest passes with `MDTEST_EXTERNAL=1`,
and `prek` passes on the changed files. One note: the markdown hook
rewrapped a single prose line in the test file, which is folded into the
commit.
## Summary
By default, Pydantic allows arbitrary extra constructor arguments, which
is simply ignored (`extra="ignore"`). This often indicates a mistake
though, so we now emit emit a new diagnostic with severity "warning":
```py
class Person(BaseModel):
name: str
admin: bool = Field(default=false)
# a typo: should be `admin`, not `admni`
Person(name="Alice", admni=true) # warning: [pydantic-discarded-extra-argument]
```
closes https://github.com/astral-sh/ty/issues/3966
## Ecosystem impact
One true positive.
## Test plan
New and updated Markdown tests
## Summary
This PR contains two loosely related features/fixes around constructor
signatures for Pydantic models:
- Recognize Pydantic's legacy `populate_by_name` configuration option as
enabling validation by both field name and alias.
- Inspect the model itself, in addition to its bases, when classifying
custom `__init__` behavior
## Test Plan
New Markdown tests
## Summary
A Pydantic model with a base class with a custom `__init__` method
previously prevented us from adding `extra: **Unknown` to the models
constructor.
## Test Plan
Added Markdown tests
## Summary
Add support for `Annotated[T, Field(...)]`, `Strict(..)` and
(transitively) also support for aliases like `StrictInt`.
One challenge here is that aliases like `StrictInt` are defined as
`StrictInt = Annotated[int, Strict()]`. When we see `StrictInt` in a
field annotation, we have already lost the `Annotated` metadata. For
now, we simply resolve this by following the alias back to it's original
definition, since it seems wrong to store `Annotated` metadata (or a
link back to its definition) inside the type for this specific use-case
only.
closes https://github.com/astral-sh/ty/issues/2130
closes https://github.com/astral-sh/ty/issues/3948
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
New and updated Markdown tests.
## Summary
`float`s that were embedded in unions were not recognized by our lax
mode mapping (since we were only looking for the expanded `float |
int`), so they were mapped to `Any` instead of `LaxFloat`, which lead to
overly permissive lax types.
closes https://github.com/astral-sh/ty/issues/3946
## Test Plan
Added a regression test
## Summary
Recognize frozen models that have `frozen=True` in their model config:
```py
class Person(BaseModel):
model_config = ConfigDict(frozen=True)
name: str
person = Person(name="Alice")
person.name = "Bob" # error: [invalid-assignment]
```
With this change, we can now also get rid of the
`DataclassTransformerParams` that were still stored in every Pydantic
model's metadata.
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated Markdown tests
## Summary
A Pydantic field which uses `...` (ellipsis) for the `default` argument
is actually required and provides no default value.
```py
class Model(BaseModel):
value: Any = Field(...)
Model() # error
```
towards https://github.com/astral-sh/ty/issues/2403
## Ecosystem
The two new diagnostics are false positives due to missing support for
`AliasChoices`. I think they are acceptable. They were missing
previously because we were modeling something completely wrong, so it's
hardly a regression (we only recently removed those diagnostics when
adding support for `extra`).
## Test Plan
Updated Markdown tests
## Summary
When a Pydantic model uses a `RootModel` as a field, that field can
either be passed as an instance of the class (`IntList`), or as the
underlying type directly (`list[int]`):
```py
class IntList(RootModel[list[int]]): ...
class Model(BaseModel):
int_list: IntList
Model(int_list=IntList([1, 2, 3])) # okay
Model(int_list=[1, 2, 3]) # also okay
Model(int_list=1) # error
```
Prior to this PR, we allowed `Any` type to be passed for `RootModel`
fields.
towards https://github.com/astral-sh/ty/issues/2403
## Ecosystem
The new diagnostic on prefect looks like a true positive.
## Test Plan
Updated Markdown tests
## Summary
Pydantic models can be configured via class keywords, via `ConfigDict`,
and also via plain dictionary literals. Here, we add support for the
third variant (the other two are already supported):
```py
class PlainDictConfig(BaseModel):
model_config = {"extra": "forbid"}
name: str
PlainDictConfig(name="Alice", something_else=7) # error: [unknown-argument]
```
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated Markdown tests
## Summary
Underscore-prefixed attributes are considered private and do not become
fields in Pydantic models:
```py
class Person(BaseModel):
name: str
_implicit_private: int
Person(name="Alice") # okay
```
## Test Plan
Updated tests
## Summary
`BaseSettings` fields can be supplied via environment variables. To
support this use case, we make all fields on these models optional by
default.
```py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
host: str
port: int
# Would succeed at runtime if HOST and PORT environment variables are set
Settings()
```
closes https://github.com/astral-sh/ty/issues/1070
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated existing Markdown tests
## Summary
If `validation_alias` is specified, it[ takes precedence over `alias`
](https://pydantic.dev/docs/validation/latest/concepts/fields#field-aliases)
for purposes of the constructor signature, so here, we implement this by
simply overriding the `alias` attribute on the field.
## Test Plan
Update Markdown tests.
## Summary
Extend the Pydantic test suite to include a few more features that we
want to support.
## Test Plan
Tested all assertions against Pydantic's runtime behavior.