我有以下格式的 JSON 数据:
{
"date": 100
"userId": 1
"data": [
{
"timeStamp": 101,
"reading": 1
},
{
"timeStamp": 102,
"reading": 2
}
]
}
{
"date": 200
"userId": 1
"data": [
{
"timeStamp": 201,
"reading": 3
},
{
"timeStamp": 202,
"reading": 4
}
]
}
Run Code Online (Sandbox Code Playgroud)
我将其读入 Spark SQL:
val df = SQLContext.read.json(...)
df.printSchema
// root
// |-- date: double (nullable = true)
// |-- userId: long (nullable = true)
// |-- data: array (nullable = true)
// | |-- element: …Run Code Online (Sandbox Code Playgroud) 我正在编写一个库,在这里我需要一个采用(可能)抽象类型并返回该类型具体子类型的实例的方法:
# script.py
from typing import Type
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
T = TypeVar('T', bound=AbstractClass)
def f(c: Type[T]) -> T:
# find concrete implementation of c based on
# environment configuration
...
f(AbstractClass) # doesn't type check
Run Code Online (Sandbox Code Playgroud)
运行mypy script.py收益:
error: Only concrete class can be given where "Type[AbstractClass]" is expected
我不明白此错误消息,并且很难找到有关该错误的任何文档。有什么方法可以注释该函数,以便进行mypy类型检查吗?
附带说明一下,PyCharm的类型检查器是我使用最多的类型检查f,没有错误。
我想在类型存根中添加一个名为的集合类List,这实际上是内置函数的包装list。出于所有实际目的,您可以假设它看起来像这样:
# library.py
class List:
def __init__(self, *values):
self.values = values
Run Code Online (Sandbox Code Playgroud)
现在,在我的存根文件library.pyi中:
# library.pyi
from typing import Generic, TypeVar, Iterable
T = TypeVar('T')
class List(Generic[T]):
def __init__(self, *values: T) -> None: ...
Run Code Online (Sandbox Code Playgroud)
如果执行以下操作,我想输入失败:
# client.py
from library import List
def f() -> List[str]:
return List(*range(10))
Run Code Online (Sandbox Code Playgroud)
但是mypy client.py以0退出。此外,python client.py失败以TypeError: 'type' object is not subscriptable。
我的理解是类型提示对运行时没有任何影响。那显然是错误的。有人可以纠正我关于类型提示如何工作的心理模型吗?
而且,有什么可以得到我想要的(即mypy client.py失败)吗?