Teach mypy that there are two possible return types here: either an Expression, or ... something else.
Not a SLOC reduction, but it does remove an assertion. It also isn't much safer than a cast, mypy has no insight into if overloads are true or not. It's on the honor system. I thought I'd demonstrate its use, though. Signed-off-by: John Snow <js...@redhat.com> --- scripts/qapi/parser.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/scripts/qapi/parser.py b/scripts/qapi/parser.py index f2b57d5642a..cbdddc344e7 100644 --- a/scripts/qapi/parser.py +++ b/scripts/qapi/parser.py @@ -23,6 +23,7 @@ Optional, Set, Union, + overload, ) from .common import match_nofail @@ -95,8 +96,7 @@ def _parse(self) -> None: self.docs.append(cur_doc) continue - expr = self.get_expr(False) - assert isinstance(expr, dict) # Guaranteed when nested=False + expr = self.get_expr() if 'include' in expr: self.reject_expr_doc(cur_doc) @@ -304,8 +304,15 @@ def get_values(self) -> List[object]: raise QAPIParseError(self, "expected ',' or ']'") self.accept() + @overload + # No nesting, must be an Expression. + def get_expr(self) -> Expression: ... + + @overload + # Possibly nested, might be anything. + def get_expr(self, nested: bool) -> _ExprValue: ... + def get_expr(self, nested: bool = False) -> _ExprValue: - # TODO: Teach mypy that nested=False means the retval is a Dict. expr: _ExprValue if self.tok != '{' and not nested: raise QAPIParseError(self, "expected '{'") -- 2.30.2