Home > database >  Python Type Hints
Python Type Hints

Time:09-30

in python 3.10 this code works, but from static code analysis I get error message from Pylance regarding "generalTypeIssue"

@dataclass
class Animal():
    name:str

class Dog(Animal):
    def bark(self):
        print("whoof")
class Snake(Animal):
    def bite(self):
        print("bite!!!")

def make_animal(animal_class: type[Animal], name: str) -> Animal:
    return animal_class(name=name)

my_dog = make_animal(animal_class=Dog, name="bello")
# type(my_dog) is <class '__main__.Dog'>
my_dog.bark() <--- cannot access member bark for Animal

How to make a func that returns instances with correct types based on the input type?

CodePudding user response:

Use a bound TypeVar to annotate the make_animal generic function

from dataclasses import dataclass
from typing import TypeVar

@dataclass
class Animal:
    name: str

T = TypeVar('T', bound=Animal)

class Dog(Animal):
    def bark(self):
        print("whoof")

class Snake(Animal):
    def bite(self):
        print("bite!!!")

def make_animal(animal_class: type[T], name: str) -> T:
    return animal_class(name=name)

my_dog = make_animal(animal_class=Dog, name="bello")
# my_dog is correctly narrowed to Dog
my_dog.bark()

CodePudding user response:

Since you already know what type you're going to instantiate, you can hint the type when assigning the value to my_dog

my_dog: Dog = make_animal(animal_class=Dog, name="bello")
  • Related