chex icon indicating copy to clipboard operation
chex copied to clipboard

Use dataclass_transform to help type checkers with @chex.dataclass

Open tmke8 opened this issue 2 years ago • 2 comments

closes #155

I basically copied this example: https://peps.python.org/pep-0681/#id1

Tested with pyright/pylance.

I had to specify a return type for chex.dataclass because otherwise pyright/pylance is ignoring it completely if arguments are passed to it (like chex.dataclass(eq=False)), but if it's used bare (just chex.dataclass without any parentheses) then it also works without the return type annotation.

There is a (expected) test failure from pytype:

FAILED: /home/tmk/dev/python/chex/.pytype/pyi/chex/_src/dataclass.pyi 
/tmp/chex-env/bin/python3 -m pytype.single --imports_info /home/tmk/dev/python/chex/.pytype/imports/chex._src.dataclass.imports --module-name chex._src.dataclass --platform linux -V 3.9 -o /home/tmk/dev/python/chex/.pytype/pyi/chex/_src/dataclass.pyi --analyze-annotated --nofail --quick /home/tmk/dev/python/chex/chex/_src/dataclass.py
File "/home/tmk/dev/python/chex/chex/_src/dataclass.py", line 90, in <module>: typing_extensions.dataclass_transform not supported yet [not-supported-yet]

I'm not sure how to deal with that.

There is also not really a way to write tests for this...

cc @hbq1

tmke8 avatar Sep 01 '22 11:09 tmke8

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

google-cla[bot] avatar Sep 01 '22 11:09 google-cla[bot]

Visual proof that it works: image

And with the decorator commented out: image

tmke8 avatar Sep 01 '22 11:09 tmke8

Unfortunately, this change breaks multiple internal tests because as you noticed, pytype doesn't properly support this feature :( When I suppress this warning, pytype generates a bunch of other errors that are apparently derived from it.

I tried several variations of applying dataclass_transformer, but none of them worked with all supported usages of chex.dataclass(). I'm afraid we'll have to wait until pytype knows how to work with this wrapper.

hbq1 avatar Oct 07 '22 10:10 hbq1