pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

`dataclasses.asdict()` should accept dataclasses

Open grievejia opened this issue 9 months ago • 5 comments

Describe the Bug

Minimal repro:

import dataclasses

@dataclasses.dataclass
class Foo:
    x: int  = 0

def test(foo: Foo) -> None:
    dataclasses.asdict(foo)

Expected: no error Actual: Argument Foo is not assignable to parameter obj with type DataclassInstance in function dataclasses.asdict

Sandbox Link

https://pyrefly.org/sandbox/?code=JYWwDg9gTgLgBAEwIYyQYwDZIM7YKbYBQhAAsqpjvtgHTnpa6GW5wBiEEAXIXH3AA8ucYADt4cALxwADMQR4AZnBgEYACkWdhHCAEo4AWgB8cAHIRReHv0QoGVAjRwJgaDVv1A

(Only applicable for extension issues) IDE Information

No response

grievejia avatar May 20 '25 18:05 grievejia

Oh DataclassInstance is a protocol that checks for the presence of __dataclass_fields__: https://github.com/python/typeshed/blob/6007267f68ed94a49421cff17b03e23a0177ad8c/stdlib/_typeshed/init.pyi#L352. So we probably just need to synthesize that field.

rchen152 avatar May 20 '25 18:05 rchen152

I'd be happy to tackle this. Can you give some guidance on this issue/where you "synthesise" fields?

Heidar-An avatar May 29 '25 00:05 Heidar-An

Thanks for offering to take this on! The place to start would be dataclasses.rs: https://github.com/facebook/pyrefly/blob/main/pyrefly/lib/alt/class/dataclass.rs. That file synthesizes a number of fields for dataclasses (e.g., get_dataclass_match_args synthesizes a __match_args__ fields: https://github.com/facebook/pyrefly/blob/509d35b65f6b06a43af874024a5d13dea58e10bc/pyrefly/lib/alt/class/dataclass.rs#L144). We would need to add a similar function to synthesize __dataclass_fields__ and add it to the map of synthesized fields here: https://github.com/facebook/pyrefly/blob/509d35b65f6b06a43af874024a5d13dea58e10bc/pyrefly/lib/alt/class/dataclass.rs#L57.

rchen152 avatar May 29 '25 00:05 rchen152

Thanks a lot for the in-detail information! I'll get started on this in about a week! (have a bit on my plate right now)

Heidar-An avatar May 30 '25 17:05 Heidar-An

I took a crack at a fix on #412. Not sure if I did it right, please let me know!

zachmullen avatar May 31 '25 17:05 zachmullen