How to express this kind of relationship between types with PEP695 annotations? Pylance (pyright) says that Self is not valid in this context
, but there seems to be no other way to express it?
The goal is to have AbstractFactory
know what kind of goods it produces, and have AbstractGood
know which kind of AbstractFactory
produced it.
# factory.py
from typing import Self
from abc import ABC
class AbstractFactory[G: AbstractGood[Self]](ABC):
def __init__(self, good_class: type[G]) -> None:
self.good_class = good_class
def produce(self) -> G:
good = self.good_class(self)
return good
class AbstractGood[F: AbstractFactory[Self]](ABC):
def __init__(self, factory: F):
self.factory = factory
# charlie.py
from factory import AbstractFactory, AbstractGood
class ChocolateFactory(AbstractFactory[ChocolateBar]):
...
class ChocolateBar(AbstractGood[ChocolateFactory]):
...