The List[Geometry] type hint on the code below does not cause self.items.append(line) to complain because line is a Line which is subclass of Geometry.
The same type hint causes the item.is_horizontal on the last line to say Unresolved attribute reference 'is_horizontal' for class 'Geometry'.
I think this happens because the is_horizontal property exists only in one of the subclasses of Geometry.
What is the correct way to avoid this warning?
With List[Union[Geometry, Line, Circle]] the warning goes away, but I'm not sure this is the correct solution. Listing a set of classes is not like saying <Geometry> and all subclasses.
class Geometry: is_circle = is_line = False class Line(Geometry): is_line = True # property on Geometry and subclasses is_horizontal = True # property only on Line class Circle(Geometry): is_circle = True # property on Geometry and subclasses radius = 10 # property only on Line class Geometries: def __init__(self): self.items: List[Geometry] = [] def add_line(self, line: Line): self.items.append(line) def horizontal_lines(self): return [item for item in self.items if item.is_line and item.is_horizontal]
is_lineandis_circleare both redundant. You can replace, e.g,item.is_linewithisinstance(item, Line).is_horizontalandradiusshould both be instance attributes, not class attributes. Not all lines are horizontal, and not all circles have radius 10.items -> List[Geometry]soitem in items: item.is_horizontalseems a valid warning. You meanitem.is_line and item.is_horizontalshould short-circuit theis_horizontalcheck?item.is_horizontalwill only be evaluated whenitemhas a runtime type ofLine. You said it was aGeometry, so it has to assume it might not be aLine. You can usecastto tell the type checker it's OK:if item.is_line and cast(Line, item).is_horizontal.