-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[ty] Support dataclasses.InitVar
#19527
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+336
−57
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0da5d0e
[ty] Support `dataclasses.InitVar`
InSyncWithFoo d531a24
Support dataclasses.InitVar
sharkdp 5f779d5
Apply suggestions from code review
sharkdp 3ae3495
Init-only attributes are available if they have a default
sharkdp c748130
Add a TypeQualifiers::name() method
sharkdp a303c87
Support InitVar attributes that are overwritten on the instance
sharkdp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
150 changes: 150 additions & 0 deletions
150
crates/ty_python_semantic/resources/mdtest/type_qualifiers/initvar.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| # `dataclasses.InitVar` | ||
|
|
||
| From the Python documentation on [`dataclasses.InitVar`]: | ||
|
|
||
| If a field is an `InitVar`, it is considered a pseudo-field called an init-only field. As it is not | ||
| a true field, it is not returned by the module-level `fields()` function. Init-only fields are added | ||
| as parameters to the generated `__init__()` method, and are passed to the optional `__post_init__()` | ||
| method. They are not otherwise used by dataclasses. | ||
|
|
||
| ## Basic | ||
|
|
||
| Consider the following dataclass example where the `db` attribute is annotated with `InitVar`: | ||
|
|
||
| ```py | ||
| from dataclasses import InitVar, dataclass | ||
|
|
||
| class Database: ... | ||
|
|
||
| @dataclass(order=True) | ||
| class Person: | ||
| db: InitVar[Database] | ||
|
|
||
| name: str | ||
| age: int | ||
| ``` | ||
|
|
||
| We can see in the signature of `__init__` that `db` is included as an argument: | ||
|
|
||
| ```py | ||
| reveal_type(Person.__init__) # revealed: (self: Person, db: Database, name: str, age: int) -> None | ||
| ``` | ||
|
|
||
| However, when we create an instance of this dataclass, the `db` attribute is not accessible: | ||
|
|
||
| ```py | ||
| db = Database() | ||
| alice = Person(db, "Alice", 30) | ||
|
|
||
| alice.db # error: [unresolved-attribute] | ||
| ``` | ||
|
|
||
| The `db` attribute is also not accessible on the class itself: | ||
|
|
||
| ```py | ||
| Person.db # error: [unresolved-attribute] | ||
| ``` | ||
|
|
||
| Other fields can still be accessed normally: | ||
|
|
||
| ```py | ||
| reveal_type(alice.name) # revealed: str | ||
| reveal_type(alice.age) # revealed: int | ||
| ``` | ||
|
|
||
| ## `InitVar` with default value | ||
|
|
||
| An `InitVar` can also have a default value. In this case, the attribute *is* accessible on the class | ||
| and on instances: | ||
sharkdp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| ```py | ||
| from dataclasses import InitVar, dataclass | ||
|
|
||
| @dataclass | ||
| class Person: | ||
| name: str | ||
| age: int | ||
|
|
||
| metadata: InitVar[str] = "default" | ||
|
|
||
| reveal_type(Person.__init__) # revealed: (self: Person, name: str, age: int, metadata: str = Literal["default"]) -> None | ||
|
|
||
| alice = Person("Alice", 30) | ||
| bob = Person("Bob", 25, "custom metadata") | ||
|
|
||
| reveal_type(bob.metadata) # revealed: str | ||
|
|
||
| reveal_type(Person.metadata) # revealed: str | ||
| ``` | ||
|
|
||
| ## Overwritten `InitVar` | ||
|
|
||
| We do not emit an error if an `InitVar` attribute is later overwritten on the instance. In that | ||
| case, we also allow the attribute to be accessed: | ||
|
|
||
| ```py | ||
| from dataclasses import InitVar, dataclass | ||
|
|
||
| @dataclass | ||
| class Person: | ||
| name: str | ||
| metadata: InitVar[str] | ||
|
|
||
| def __post_init__(self, metadata: str) -> None: | ||
| self.metadata = f"Person with name {self.name}" | ||
|
|
||
| alice = Person("Alice", "metadata that will be overwritten") | ||
|
|
||
| reveal_type(alice.metadata) # revealed: str | ||
| ``` | ||
|
|
||
| ## Error cases | ||
|
|
||
| ### Syntax | ||
|
|
||
| `InitVar` can only be used with a single argument: | ||
|
|
||
| ```py | ||
| from dataclasses import InitVar, dataclass | ||
|
|
||
| @dataclass | ||
| class Wrong: | ||
| x: InitVar[int, str] # error: [invalid-type-form] "Type qualifier `InitVar` expected exactly 1 argument, got 2" | ||
| ``` | ||
|
|
||
| A bare `InitVar` is not allowed according to the [type annotation grammar]: | ||
|
|
||
| ```py | ||
| @dataclass | ||
| class AlsoWrong: | ||
| x: InitVar # error: [invalid-type-form] "`InitVar` may not be used without a type argument" | ||
| ``` | ||
|
|
||
| ### Outside of dataclasses | ||
|
|
||
| `InitVar` annotations are not allowed outside of dataclass attribute annotations: | ||
|
|
||
| ```py | ||
| from dataclasses import InitVar, dataclass | ||
|
|
||
| # error: [invalid-type-form] "`InitVar` annotations are only allowed in class-body scopes" | ||
| x: InitVar[int] = 1 | ||
|
|
||
| def f(x: InitVar[int]) -> None: # error: [invalid-type-form] "`InitVar` is not allowed in function parameter annotations" | ||
| pass | ||
|
|
||
| def g() -> InitVar[int]: # error: [invalid-type-form] "`InitVar` is not allowed in function return type annotations" | ||
| return 1 | ||
|
|
||
| class C: | ||
| # TODO: this would ideally be an error | ||
| x: InitVar[int] | ||
|
|
||
| @dataclass | ||
| class D: | ||
| def __init__(self) -> None: | ||
| self.x: InitVar[int] = 1 # error: [invalid-type-form] "`InitVar` annotations are not allowed for non-name targets" | ||
| ``` | ||
|
|
||
| [type annotation grammar]: https://typing.python.org/en/latest/spec/annotations.html#type-and-annotation-expressions | ||
| [`dataclasses.initvar`]: https://docs.python.org/3/library/dataclasses.html#dataclasses.InitVar | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.