Home > OS >  Subclass not valid as input to list of Superclass / type hinting in python
Subclass not valid as input to list of Superclass / type hinting in python

Time:08-22

I've got this piece of code, where I want to add subclasses of an abstract class to a list of items, specified as a List of the superclass:

from typing import List

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

class ShoppingBasket:
    def __init__(self, *items: List[Product]):
        self.items = items

basket = ShoppingBasket(Food, Drink)
print(basket.items)

But Visual Studio Code analysis of the code concludes with a squiggle under the Food and Drink parameter, with the text:

Argument of type "Type[Food]" cannot be assigned to parameter "items" of type "List[Product]" in function "__init__" "Type[type]" is incompatible with "Type[List[Product]]"PylancereportGeneralTypeIssues"

I'm aware that Product isn't a proper metaclass/abstract, but how can I avoid this message?

CodePudding user response:

For type hints on a *args parameter, you give the type of the individual arguments rather than the collection of arguments (which would be a Tuple). You're also passing a type rather than an instance, so you need something that fits Type[Food] like the message says.

from typing import Type

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

class ShoppingBasket:
    def __init__(self, *items: Type[Product]):
        self.items = items

basket = ShoppingBasket(Food, Drink)
print(basket.items)

This produces no mypy errors for me.

  • Related