Pyright: Support for type hinting non specific dataclasses

Created on 18 Apr 2020  路  2Comments  路  Source: microsoft/pyright

Is your feature request related to a problem? Please describe.
I wanted to type hint a class to only accept dataclasses as inputs. Searching a bit on the web I found a (at least to me) reasonable solution on StackOverflow based on defining a Protocol.

From the same author, there is also an open issue on mypy, which might give even more context.

from dataclasses import dataclass
from typing import Dict, Protocol


class IsDataclass(Protocol):
    # checking for this attribute seems to currently be
    # the most reliable way to ascertain that something is a dataclass
    __dataclass_fields__: Dict


def dataclass_only(x: IsDataclass):
    ...  # do something that only makes sense with a dataclass


@dataclass
class A:
    pass


dataclass_only(A())  # a static type check should show that this line is fine

Describe the solution you'd like
Pyright should recognize that any class wrapped in @dataclass will support the above Protocol, and thus show that the last line is valid.

addressed in next version enhancement request

Most helpful comment

This is now implemented in version 1.1.33, which I just published.

All 2 comments

Thanks for the suggestion. This will be implemented in the next published version of pyright.

This is now implemented in version 1.1.33, which I just published.

Was this page helpful?
0 / 5 - 0 ratings