Skip to content

Commit 2e2d930

Browse files
jnsnowphilmd
authored andcommitted
python/qmp.py: add casts to JSON deserialization
mypy and python type hints are not powerful enough to properly describe JSON messages in Python 3.6. The best we can do, generally, is describe them as Dict[str, Any]. Add casts to coerce this type for static analysis; but do NOT enforce this type at runtime in any way. Note: Python 3.8 adds a TypedDict construct which allows for the description of more arbitrary Dictionary shapes. There is a third-party module, "Pydantic", which is compatible with 3.6 that can be used instead of the JSON library that parses JSON messages to fully-typed Python objects, and may be preferable in some cases. (That is well beyond the scope of this commit or series.) Signed-off-by: John Snow <[email protected]> Reviewed-by: Kevin Wolf <[email protected]> Message-Id: <[email protected]> Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
1 parent ef5d474 commit 2e2d930

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

python/qemu/qmp.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import logging
1414
from typing import (
1515
Any,
16+
cast,
1617
Dict,
1718
Optional,
1819
TextIO,
@@ -130,7 +131,10 @@ def __json_read(self, only_event=False):
130131
data = self.__sockfile.readline()
131132
if not data:
132133
return None
133-
resp = json.loads(data)
134+
# By definition, any JSON received from QMP is a QMPMessage,
135+
# and we are asserting only at static analysis time that it
136+
# has a particular shape.
137+
resp: QMPMessage = json.loads(data)
134138
if 'event' in resp:
135139
self.logger.debug("<<< %s", resp)
136140
self.__events.append(resp)
@@ -262,7 +266,7 @@ def command(self, cmd, **kwds):
262266
ret = self.cmd(cmd, kwds)
263267
if 'error' in ret:
264268
raise QMPResponseError(ret)
265-
return ret['return']
269+
return cast(QMPReturnValue, ret['return'])
266270

267271
def pull_event(self, wait=False):
268272
"""

0 commit comments

Comments
 (0)