Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type annotations with subclasses and list of class

For classes that naturally contain lists of other instances of themselves, what is the correct way to note this in Python type annotations such that subclasses work.

To give something concrete for discussion, here is an example using a base tree type and a subclass.

from typing import List, Optional, TypeVar

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

class TreeBase(object):
    def __init__(self : T) -> None:
        self.parent = None # type: Optional[T]
        self.children = [] # type: List[T]

    def addChild(self : T, node : T) -> None:
        self.children.append(node)
        node.parent = self

class IdTree(TreeBase):
    def __init__(self, name : str) -> None:
        super().__init__()
        self.id = name      

    def childById(self : 'IdTree', name : str) -> Optional['IdTree']:
        for child in self.children:
            if child.id == name: # error: "T" has no attribute "id"
                return child # error: Incompatible return value type (got "T", expected "Optional[IdTree]")
        return None

I get errors in mypy versions 0.600 (pip3 default) and 0.650 (latest from github).

What is the correct way of specifying this?

like image 609
MaresEatOats Avatar asked Mar 05 '26 03:03

MaresEatOats


1 Answers

Try making the whole class Generic with the type var.

I don't think you need to annotate self in TreeBase either, since you're not returning it from these methods or otherwise using it in a generic way.

from typing import Generic, List, Optional, TypeVar

T = TypeVar("T", bound="TreeBase")


class TreeBase(Generic[T]):
    def __init__(self) -> None:
        self.parent: Optional[T] = None
        self.children: List[T] = []

    def addChild(self, node: T) -> None:
        self.children.append(node)
        node.parent = self


class IdTree(TreeBase["IdTree"]):  # No TypeVar, subclass is non-generic.
    def __init__(self, name: str) -> None:
        super().__init__()
        self.id = name

    def childById(self, name: str) -> Optional["IdTree"]:
        for child in self.children:
            if child.id == name:
                return child
        return None
like image 190
gilch Avatar answered Mar 06 '26 17:03

gilch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!