Search code examples
pythonpython-typingpython-dataclasses

Python: how to type hint a dataclass?


The code below works, but I'm getting the following warning by PyCharm:

Cannot find reference __annotations__ in '(...) -> Any'.

I guess it's because I'm using Callable. I didn't find something like Dataclass. Which type should I use instead?

from __future__ import annotations
from dataclasses import dataclass
from typing import Callable

@dataclass
class Fruit:
  color: str
  taste: str

def get_cls() -> Callable:
  return Fruit

attrs = get_cls().__annotations__  # <- IDE warning
print(attrs)

Solution

  • In this particular example you can just hint it directly:

    from dataclasses import dataclass
    
    @dataclass
    class Fruit:
        x: str
    
    def get_cls() -> type[Fruit]:
        return Fruit
    
    attrs = get_cls().__annotations__
    print(attrs)
    
    $ python d.py
    {'x': <class 'str'>}
    $ mypy d.py
    Success: no issues found in 1 source file
    

    However I don't know if this is what you're asking. Are you after a generic type for any dataclass? (I would be tempted just to hint the union of all possible return types of get_cls(): the whole point about using a dataclass rather than e.g. a dict is surely to distinguish between types of data. And you do want your typechecker to warn you if you try to access attributes not defined on one of your dataclasses.)

    References

    See the docs on typing.Type which is now available as type (just like we can now use list and dict rather than typing.List and typing.Dict).