שחמט - Union ו mypy

בשביל שאני אוכל ליצור לוח פעם עם חד קרן ופעם בלי, ובלי לשכפל קוד, הוספתי משתנה בוליאני שלפי זה הקוד משנה את ה Rook ל Unicorn. הקוד עובד, הבעיה ש mypy זורק לי שגיאה.

הקוד:

        rook_or_unicorn = Rook
        if use_unicorn:
            rook_or_unicorn = Unicorn

ה Annotation:
Union[Rook, Unicorn]
והשגיאה:

  • Expected type ‘Union[Rook, Unicorn]’, got ‘Type[Union[Unicorn, Rook]]’ instead

אוקיי, ההבחנה פה היא קצת טריקית:
המשתנה rook_or_unicorn הוא לא מסוג Rook, הוא עצמו ממש הערך Rook.
מה שאתה צריך לשאול את עצמך הוא “מה הסוג של Rook?” או “איך עושים אנוטציה לסוג של Rook?”

האם הכוונה ל:
Type[Union[Rook, Unicorn]]?
זה סידר את הערה הראשונה, אבל הערה שנבעה ממנה עדיין קיימת.
בסוף הפונקציה:

return self._generate_back_row(order_white, Color.WHITE)

אני מקבל הערה על order_white:

  • Expected type ‘Tuple[Any, …]’ (matched generic type ‘Tuple[TParent, …]’), got ‘Tuple[Type[Union[Rook, Unicorn]], Type[Knight], Type[Bishop], Type[Bishop], Type[Queen], Type[King], Type[Wildebeest], Type[Camel], Type[Camel], Type[Knight], Type[Union[Rook, Unicorn]]]’ instead

כאשר TParent זה:
TParent = TypeVar(‘TParent’, bound=Piece)

וה Annotation:
order: Tuple[TParent, …]