Python type hinting a deque filled with myclass objects

我的未来我决定 提交于 2020-03-22 09:23:37

问题


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())

回答1:


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.



来源:https://stackoverflow.com/questions/51944520/python-type-hinting-a-deque-filled-with-myclass-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!