Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting a deque filled with myclass objects

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())
like image 389
576i Avatar asked Aug 21 '18 08:08

576i


1 Answers

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.

like image 172
Michael0x2a Avatar answered Jan 05 '23 15:01

Michael0x2a