Skip to content

Commit

Permalink
Add AttrsInstance protocol to forgotten attrs.asdict and attrs.astuple (
Browse files Browse the repository at this point in the history
#1090)

* Add AttrsInstance protocol to forgotten attrs.asdict and attrs.astuple

* Add mypy test for attrs.asdict

* Add changelog entry for attrs.asdict

* Clarify it's about type stubs

Co-authored-by: Hynek Schlawack <hs@ox.cx>
  • Loading branch information
tsx and hynek committed Jan 23, 2023
1 parent 14354bb commit 882805e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog.d/1090.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`attrs.asdict()`'s and `attrs.astuple()`'s type stubs now accept the `attrs.AttrsInstance` protocol.
4 changes: 2 additions & 2 deletions src/attrs/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ from attr import validators as validators

# TODO: see definition of attr.asdict/astuple
def asdict(
inst: Any,
inst: AttrsInstance,
recurse: bool = ...,
filter: Optional[_FilterType[Any]] = ...,
dict_factory: Type[Mapping[Any, Any]] = ...,
Expand All @@ -59,7 +59,7 @@ def asdict(

# TODO: add support for returning NamedTuple from the mypy plugin
def astuple(
inst: Any,
inst: AttrsInstance,
recurse: bool = ...,
filter: Optional[_FilterType[Any]] = ...,
tuple_factory: Type[Sequence[Any]] = ...,
Expand Down
19 changes: 19 additions & 0 deletions tests/test_mypy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1372,6 +1372,25 @@
fields(A) # E: Argument 1 to "fields" has incompatible type "Type[A]"; expected "Type[AttrsInstance]" [arg-type]
- case: testAsDict
main: |
from attrs import asdict, define
@define
class A:
a: int
asdict(A(1))
- case: testAsDictError
main: |
from attrs import asdict
class A:
a: int
asdict(A()) # E: Argument 1 to "asdict" has incompatible type "A"; expected "AttrsInstance" [arg-type]
- case: testHasTypeGuard
main: |
from attrs import define, has
Expand Down

0 comments on commit 882805e

Please sign in to comment.