<p>我花了一段时间才记住要使用哪种类型,但我想知道您想使用哪种类型的<a href="https://docs.python.org/3/library/typing.html#typing.cast" rel="nofollow noreferrer">cast</a></p>
<p>与它在其他语言中的使用不同,<strong>cast(x,y)</strong>不做任何事,但它告诉键入<em>将y视为类型x</em>。运行时,它是一个no-op,只返回y</p>
<p><strong>就像编译语言一样,如果我阅读它,我会特别注意代码:这真的在运行时起作用吗?数据类型是否正确?</strong>:</p>
<ul>
<li>如果不能保证以后生成数据的内容只会发出<code>SpecificData</code>,那么使用LSP注释的重复闭包是合适的。如果可以的话,铸造就可以了。您的最小示例缺少该位,但是如果您已经显示了实际数据通过<code>print(data)</code>,那么我们就知道是否应用了LSP</李>
</ul>
<pre><code>from typing import Callable, Any, cast
class Data:
pass
class SpecificData(Data):
pass
class Event:
pass
class SpecificEvent(Event):
pass
def detect_specific_event(data: SpecificData, other_info: str) -> SpecificEvent:
return SpecificEvent()
def run_detection(callback: Callable[[Data, Any], Event]) -> None:
return
run_detection(cast((Callable[[Data, Any], Event]),detect_specific_event))
</code></pre>
<p>在这里,你基本上告诉打字,“接受我的话”,即<code>detect_specific_event</code>是一个<code>Callable[[Data, Any], Event])</code></p>
<p>运行和类型检查的输出:</p>
<pre><code>$ mypy test2.py
Success: no issues found in 1 source file
$ python test2.py
(venv)$ 😃 well your code says nothing.
</code></pre>
<p>将cast更改为实际sig:</p>
<p><code>run_detection(cast((Callable[[SpecificData, Any], SpecificEvent]),detect_specific_event))</code></p>
<pre><code>(venv) $@so.mypy$ mypy test2.py
Argument 1 to "run_detection" has incompatible type "Callable[[SpecificData, Any], SpecificEvent]"; expected "Callable[[Data, Any], Event]"
Found 1 error in 1 file (checked 1 source file)
$ python test2.py
$😃 well your code says nothing.
</code></pre>