Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best generic type hint for a dataclass in python?

I have started using dataclasses and I have some specific one lets say for example:

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    job:str
    
@dataclass
class Animal:
    name: str
    age: int

I then have an abstract class like an interface

import abc
from typing import List, Dict


class NameFinder:
    @abc.abstractmethod
    def get_name(self, name: str,being ) :
        pass

class PersonName(NameFinder):
    def get_name(self, name:str, person:Person):
        return person.name

class AnimalName(NameFinder):
    def get_name(self, name:str, animal:Animal):
        return animal.name

what is a good generic type hint i can use in the abstract class as placeholder for both the Person and the Animal classes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can define a protocol class, which just asserts the existence of a name attribute.

from typing import Protocol


class Named(Protocol):
    name: str


class NameFinder:
    @staticmethod
    def get_name(obj: Named) -> str:
        return obj.name

# or ...
def name_finder(obj: Named) -> str:
    return obj.name

get_name and name_finder can both accept arguments of type Person or Animal, as both classes define a name attribute for their instances. There’s no need to explicitly mark the classes as implementing the Named protocol.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading