考虑一个示例JSON文件:
[
{"name": "alex"},
{"name": "roger"},
{"name": "lily"},
{"name": "billy"}
]
可以很容易地从磁盘与磁盘进行交互,如下所示:
import os
import json
from contextlib import contextmanager
@contextmanager
def documentDB(file_name):
with open(file_name, mode='rt') as fp:
cur = json.load(fp)
yield cur
with open(file_name, mode='wt') as fp:
json.dump(cur, fp)
return
# following code works nicely
with documentDB("sample.json") as dbCur:
print(dbCur)
但是我如何断言/暗示上面代码中的dbCur
应该是dict对象的列表?我试过这个:
from typing import List
# does not work
with documentDB("sample.json") as dbCur: List[dict]:
print(dbCur)
但是我遇到了语法错误。
答案 0 :(得分:0)
取决于您要实现的目标,但如果类型提示适用于IDE,则大部分时间将理解以下内容作为dbCur的类型提示:
from typing import List
with documentDB("sample.json") as dbCur: # type: List[dict]
print(dbCur)