Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type hint for an instance of a non specific dataclass

I have a function that accepts an instance of any dataclass. what would be an appropriate type hint for it ?

haven't found something official in the python documentation


this is what I have been doing, but i don't think it's correct

from typing import Any, NewType

DataClass = NewType('DataClass', Any)
def foo(obj: DataClass):
    ...

another idea is to use a Protocol with these class attributes __dataclass_fields__, __dataclass_params__.

like image 204
moshevi Avatar asked Feb 13 '19 10:02

moshevi


2 Answers

Despite its name, dataclasses.dataclass doesn't expose a class interface. It just allows you to declare a custom class in a convenient way that makes it obvious that it is going to be used as a data container. So, in theory, there is little opportunity to write something that only works on dataclasses, because dataclasses really are just ordinary classes.

In practice, there a couple of reasons why you would want to declare dataclass-only functions anyway, and something like this is how you should go about it:

from dataclasses import dataclass from typing import Dict, Protocol   class IsDataclass(Protocol):     # as already noted in comments, checking for this attribute is currently     # 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 Foo:     pass  class Bar:     pass  dataclass_only(Foo())  # a static type check should show that this line is fine .. dataclass_only(Bar())  # .. and this one is not 

This approach is also what you alluded to in your question. If you want to go for it, keep in mind that you'll need a third party library such as mypy to do the static type checking for you, and if you are on python 3.7 or earlier, you need to manually install typing_extensions since Protocol only became part of the standard library in 3.8.


When I first wrote it, this post also featured The Old Way of Doing Things, back when we had to make do without type checkers. I'm leaving it up, but it's not recommended to handle this kind of feature with runtime-only failures any more:

from dataclasses import is_dataclass  def dataclass_only(x):     """Do something that only makes sense with a dataclass.          Raises:         ValueError if something that is not a dataclass is passed.              ... more documentation ...     """     if not is_dataclass(x):         raise ValueError(f"'{x.__class__.__name__}' is not a dataclass!")     ... 
like image 130
Arne Avatar answered Sep 20 '22 01:09

Arne


There is a helper function called is_dataclass that can be used, its exported from dataclasses.

Basically what it does is this:

def is_dataclass(obj):
    """Returns True if obj is a dataclass or an instance of a
    dataclass."""
    cls = obj if isinstance(obj, type) else type(obj)
    return hasattr(cls, _FIELDS) 

It gets the type of the instance using type, or if the object extends type, the object itself.

It then checks if the variable _FIELDS, which equals __dataclass_fields__, exists on this object. This is basically equivalent to the other answers here.

To "type" dataclass i would do something like this:


class DataclassProtocol(Protocol):
    __dataclass_fields__: Dict
    __dataclass_params__: Dict
    __post_init__: Optional[Callable]
like image 27
Na'aman Hirschfeld Avatar answered Sep 21 '22 01:09

Na'aman Hirschfeld