Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add variable type annotation for what goes into a Queue?

Tags:

python

types

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"

like image 866
rawr rang Avatar asked Jan 10 '20 21:01

rawr rang


People also ask

What is a variable annotation?

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.

What do type annotations do?

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.


1 Answers

It is now (as of Python 3.9) possible to subscript Queue:

a: Queue[int] = Queue()  # valid
like image 178
Jasha Avatar answered Sep 29 '22 00:09

Jasha