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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With