Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Dataclass fields

## Basic

```py
from dataclasses import dataclass, field

@dataclass
class Member:
name: str
role: str = field(default="user")
tag: str | None = field(default=None, init=False)

# TODO: this should not include the `tag` parameter, since it has `init=False` set
# revealed: (self: Member, name: str, role: str = Unknown, tag: str | None = Unknown) -> None
reveal_type(Member.__init__)

alice = Member(name="Alice", role="admin")
reveal_type(alice.role) # revealed: str
alice.role = "moderator"

# TODO: this should be an error, `tag` has `init=False`
bob = Member(name="Bob", tag="VIP")
```

## The `field` function

```py
from dataclasses import field

# TODO: this should be `Literal[1]`. This is currently blocked on enum support, because
# the `dataclasses.field` overloads make use of a `_MISSING_TYPE` enum, for which we
# infer a @Todo type, and therefore pick the wrong overload.
reveal_type(field(default=1)) # revealed: Unknown
```
Copy link
Contributor

Choose a reason for hiding this comment

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

I thought this was because of a different issue in the overload evaluation code itself? Ref astral-sh/ty#267 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks, forgot about that. Not sure if it's really the same though? The overloads for dataclasses.field look different from the ones for attrs.field. Here's a simplified version of the dataclasses.field overloads:

https://play.ty.dev/c5424d2e-ac73-4759-a31e-e3fb4eed1420

If I change that to use a simple class as a sentinel value, instead of an enum (for which we infer a dynamic @Todo type), it works fine:

https://play.ty.dev/3d16e359-69db-4265-b253-5c1d6d0e3b3b

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh yes, these indeed look to be different issues. It seems I was conflating attrs.field and dataclasses.field. Thank you for the examples!

The issue I linked above will still come to bite us later on though, since ty should ideally also understand attrs.field.