问题
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