Python 类型提示填充了 myclass 对象的双端队列 [英] Python type hinting a deque filled with myclass objects
问题描述
使用 Python 3.6 或更新版本,我想键入一个函数 myfunc 来返回 MyClass 的对象.
我如何暗示 myqueue 是一个充满 MyClass 对象的 deque?
from collections import dequeglobal_queue = deque()类我的类:经过def myfunc(myqueue=global_queue) ->我的课:返回 myqueue.popleft()对于范围内的我(10):global_queue.append(MyClass())
在 Python 3.9 中,您可以直接使用 deque['MyClass']()
.
如果您使用的是 Python 3.6.1 或更高版本,您可以使用 typing.Deque
:
from 输入 import Deque从集合导入双端队列global_queue: Deque['MyClass'] = deque()类我的类:经过def myfunc(myqueue: Deque[MyClass] = global_queue) ->我的课:返回 myqueue.popleft()对于范围内的我(10):global_queue.append(MyClass())
或者,您可以改为执行 global_queue = Deque['MyClass']()
—— 在运行时,这将构造一个 collections.deque
对象.>
如果您需要支持 Python 3.5,请安装 typing_extensions
3rd 方库并执行 from typing_extensions import Deque
.该库包含类型的向后移植,这些类型是在将 Typing 模块首次添加到标准库之后添加的.
using Python 3.6 or newer, I want to type hint a function myfunc that returns an object of MyClass.
How can I hint, that myqueue is a deque filled with MyClass objects?
from collections import deque
global_queue = deque()
class MyClass:
pass
def myfunc(myqueue=global_queue) -> MyClass:
return myqueue.popleft()
for i in range(10):
global_queue.append(MyClass())
In Python 3.9, you can use deque['MyClass']()
directly.
If you are using Python 3.6.1 or higher, you can use typing.Deque
:
from typing import Deque
from collections import deque
global_queue: Deque['MyClass'] = deque()
class MyClass:
pass
def myfunc(myqueue: Deque[MyClass] = global_queue) -> MyClass:
return myqueue.popleft()
for i in range(10):
global_queue.append(MyClass())
Alternatively, you can do global_queue = Deque['MyClass']()
instead -- at runtime, that'll construct a collections.deque
object.
If you need to support Python 3.5, install the typing_extensions
3rd party library and do from typing_extensions import Deque
. That library contains backports of types that were added after the typing module was first added to the standard library.
这篇关于Python 类型提示填充了 myclass 对象的双端队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!