Don't you understand the comments of python generics?

I python novice, when flipping through python.org/dev/peps/pep-0484/-sharpthe-type-of-class-objects" rel=" nofollow noreferrer "> pep484 , and mypy , I encountered something I didn"t understand, as follows:

-sharp Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push("x") -sharp Type error

my personal understanding is:

  • T indicates any type
  • Stack [int] means Stack can only store int types, so if a string is passed below, an error can be reported
  • .

doubts are:

  • I don"t know if the above understanding is correct
  • .
  • if I had identified the data types in the heap in the first place, why would I create a generic type?
  • does generics have any usage scenarios in python ? I haven"t come into contact with languages such as java , so I think it"s very abstract to look at the examples, and I don"t know how to use them in the above scenarios.

I have just come into contact with python . Please forgive me if there are any misunderstandings. I hope my seniors will be able to solve the doubts.

Apr.15,2021

  • to
  • if we don't use generics, then we need IntStack / StrStack . If only the basic type is OK, the trouble is that in the future we have to TupleIntStrStack / TupleIntIntStrStrStack / MyLittleClassStack / MyLargeClassStack , each of which has to be redeclared, which is too troublesome
  • .
  • generics are mainly used for containers, such as stacks and queues. My most commonly used container now is concurrent.futures.Future .
  • generics are still widely used in the strongly typed language (Java), but the utilization of mypy is really low, so generics don't seem to have much usage scenarios. If you force every program (especially a library) to have a type identification, there are many examples.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c048-2b022.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c048-2b022.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?