e.g.
from queue import Queue
q: Queue = Queue()
q.put("abc")
This is okay. Now I want to specify the types that go into the queue.
from queue import Queue
q: Queue[str] = Queue()
q.put("abc")
This gets "TypeError: 'type' object is not subscriptable"
Variable Annotation is basically an enhancement of type hinting, which was introduced in Python 3.5. The full explanation behind Variable Annotation is explained in PEP 526. In this article, we give have a quick refresher on type hinting and then introduce the new Variable Annotation syntax.
Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.
It is now (as of Python 3.9) possible to subscript Queue
:
a: Queue[int] = Queue() # valid
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