How do I specify a return type for the self class type?

I want to use typing in Python to keep things clear, and am trying to figure out the right way to specify the return type from a method on a class that returns a list of instances of that class. I can use the class name on variable definitions within the class, but it fails on the return type:

from typing import List

class CheckerBoardState:

    #Python is flagging this return type as an error
    def get_next_states(self)->List[CheckerBoardState]:
        #Python thinks these definitions are okay
        move_list:List[CheckerBoardState] = []
        capture_list:List[CheckerBoardState] = []

        ...

How am I expected to do this?

Quote it: Forward references

Example from there:

class Tree:
    ...
    def leaves(self) -> List['Tree']:
        ...
2 Likes

Or from __future__ import annotations:

from __future__ import annotations

class Tree:
    ...
    def leaves(self) -> List[Tree]:
        ...
2 Likes

You can also use typing.Self, though there is a subtle difference. That represents the type of self/cls, so using that means if method is called on a subclass it should produce that subclass, not the parent. On the other hand using the class name directly indicates it’s always exactly that class. If there aren’t any subclasses (enforceable with typing.final), they’re equivalent though.

2 Likes

Would’ve been helpful to provide links…

PEP 563 – Postponed Evaluation of Annotations

typing.Self