Skip to content Skip to sidebar Skip to footer

How To Add Hint To A Factory Method?

I'm looking for a way to annotate return type of a factory function. It returns random child of 'AlgorithmBase'. class AlgorithmFactory: _algorithm_types = AlgorithmBase.__subc

Solution 1:

The problem here wasn't return type, but '_algorithm_types'. mypy has no way to understand what type it is, so it assumed that it is like return type and got error.

The following code fix the issue:

_algorithm_types: List[Type[AlgorithmBase]] = AlgorithmBase.__subclasses__()

Solution 2:

As far as I can tell this should work, but it seems like one or more of your AlgorithmBase subclasses doesn't implement these two abstract methods.

Running MyPy for

import abc

classAlgorithmBase(abc.ABC):
    @abc.abstractmethoddefget_constraints(self):
        raise NotImplementedError

    @abc.abstractmethoddefsatisfy_constraints(self):
        raise NotImplementedError


classSomeAlgorithm(AlgorithmBase):
    passclassAlgorithmFactory:
    defget(self) -> AlgorithmBase:
        algorithm = SomeAlgorithm()
        return algorithm

yields the same error you get, and it runs without any error once the methods are implemented.

import abc

classAlgorithmBase(abc.ABC):
    @abc.abstractmethoddefget_constraints(self):
        raise NotImplementedError

    @abc.abstractmethoddefsatisfy_constraints(self):
        raise NotImplementedError


classSomeAlgorithm(AlgorithmBase):
    defget_constraints(self):
        passdefsatisfy_constraints(self):
        passclassAlgorithmFactory:
    defget(self) -> AlgorithmBase:
        algorithm = SomeAlgorithm()
        return algorithm

Post a Comment for "How To Add Hint To A Factory Method?"