I have an external function that works like a factory and returns instances of different classes with a common parent type: e.g.
class Printer:
def make(self, blueprint:str) -> Blueprint: ...
class PrintA(Blueprint):
def a_specific(self) -> int: ...
class PrintB(Blueprint):
def b_specific(self, args):
"""docstring"""
a : PrintA = Printer().make("A")
b : PrintB = Printer().make("B")
# TypeHint: "(variable) a: Blueprint"
# TypeHint: "(variable) b: Blueprint"
# Usage:
result = a.a_specific() # function & type of result not detected : Any
b.b_specific(arg) # function not detected, parameters and description unknown : Any
The problem is that a and b have Blueprint as their given type hint.
How can I force the correct type hint onto the variables, so that the child functions can be detected by my IDE?
I tried to use # type: ignore[override] but that does not seem applicable for this purpose as its no error; is there by chance another magic comment command to indicate that the type checker should trust the human annotation?
Notes: I cannot adjust Printer or the Blueprints itself. Modify a matching *.pyi file is possible but should be minimal.
The amount of Blueprints is large.
Not sure if relevant but using VS-Code and Python Extension for type hinting.
At least in my example PrintA and PrintB cannot be instantiated directly via Python and Printer has to be used to initialize them.
A possible method that helps static type checkers is type casting using
typing.cast:The IDE and static type checkers should now recognize
aandbcorrectly.Unlike assertions, there is no runtime check to ensure the cast is accurate, so be careful.