I just encountered code like this:
if hasattr(x, 'initialize'):
x.initialize()
The type of x was an ABC but it doesn't include initialize. This can be easily worked around by rewriting it like this:
if hasattr(x, 'initialize'):
cast(Any, x).initialize()
However, mypy could do better, plausibly. For example:
- If
x has a union type, infer only union item types with attribute initialize after the hasattr check. So if type of x is Union[str, X] and X has initialize, infer type of x to be X in the if body.
- Allow specifying "potentially undefined" attributes in types. Accessing these requires a
hasattr check (a little like Optional[...] requiring something like an is not None check). Not sure what the syntax for this would be like. It would be nice to support these in ABCs as well.
I just encountered code like this:
The type of
xwas an ABC but it doesn't includeinitialize. This can be easily worked around by rewriting it like this:However, mypy could do better, plausibly. For example:
xhas a union type, infer only union item types with attributeinitializeafter thehasattrcheck. So if type ofxisUnion[str, X]andXhasinitialize, infer type ofxto beXin the if body.hasattrcheck (a little likeOptional[...]requiring something like anis not Nonecheck). Not sure what the syntax for this would be like. It would be nice to support these in ABCs as well.