Chr*_*lan 5 python python-3.x python-3.5 python-3.6 python-typing
我是 Python 3 中的静态类型提示的忠实粉丝和拥护者。我已经使用它们一段时间了,没有任何问题。
我刚刚遇到了一个我似乎无法编译的新边缘案例。如果我想定义一个自定义类型,然后定义它的参数怎么办?
例如,这在 Python 3 中很常见:
from typing import List, NewType
CustomObject = NewType('CustomObject', List[int])
def f(data: List[CustomObject]):
# do something
Run Code Online (Sandbox Code Playgroud)
但这不会编译:
class MyContainer():
# some class definition ...
from typing import NewType
SpecialContainer = NewType('SpecialContainer', MyContainer)
def f(data: SpecialContainer[str]):
# do something
Run Code Online (Sandbox Code Playgroud)
我意识到SpecialContainer在这种情况下这在技术上是一个函数,但它不应该在类型签名的上下文中被评估为一个函数。第二个代码片段失败,TypeError: 'function' object is not subscriptable.
您必须从头开始设计您的类以接受静态类型提示。这不满足我最初的用例,因为我试图声明第 3 方类的特殊子类型,但它编译了我的代码示例。
from typing import Generic, TypeVar, Sequence, List
# Declare your own accepted types for your container, required
T = TypeVar('T', int, str, float)
# The custom container has be designed to accept types hints
class MyContainer(Sequence[T]):
# some class definition ...
# Now, you can make a special container type
# Note that Sequence is a generic of List, and T is a generic of str, as defined above
SpecialContainer = TypeVar('SpecialContainer', MyContainer[List[str]])
# And this compiles
def f(data: SpecialContainer):
# do something
Run Code Online (Sandbox Code Playgroud)
我的初衷是创建一个类型提示,解释函数如何f()获取pd.DataFrame由整数索引且其单元格都是字符串的对象。使用上面的答案,我想出了一种人为的表达方式。
from typing import Mapping, TypeVar, NewType, NamedTuple
from pandas import pd
# Create custom types, required even if redundant
Index = TypeVar('Index')
Row = TypeVar('Row')
# Create a child class of pd.DataFrame that includes a type signature
# Note that Mapping is a generic for a key-value store
class pdDataFrame(pd.DataFrame, Mapping[Index, Row]):
pass
# Now, this compiles, and explains what my special pd.DataFrame does
pdStringDataFrame = NewType('pdDataFrame', pdDataFrame[int, NamedTuple[str]])
# And this compiles
def f(data: pdStringDataFrame):
pass
Run Code Online (Sandbox Code Playgroud)
如果您正在编写一个类似于容器泛型(如 、 或 )的自定义类,Sequence那么Mapping就Any使用它。可以自由地将类型变量添加到类定义中。
如果您尝试注释未实现类型提示的第 3 方类的特定用法:
MyOrderedDictType = NewType('MyOrderedDictType', Dict[str, float])| 归档时间: |
|
| 查看次数: |
1241 次 |
| 最近记录: |