Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "type" not a keyword in Python?

In Python 3.12 we have type aliases like this:

Python 3.12.4+ (heads/3.12:99bc8589f0, Jul 27 2024, 11:20:07) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type S = str
>>> S
S

By this syntax I assumed that, from now, the type word is considered a keyword, but it's not:

>>> type = 2
>>> 

and also:

>>> import keyword
>>> keyword.iskeyword('type')
False
like image 246
Amir reza Riahi Avatar asked Oct 18 '25 14:10

Amir reza Riahi


1 Answers

The PEG parser introduced in Python 3.9 is a lot more flexible than the old parser, so it's just capable of handling this kind of thing. Trying to make type a keyword would have broken too much existing code, so they just... didn't.

match/case is a similar story - making those keywords would have broken way too much code, such as everything that uses re.match. async used to be treated similarly, although since it was introduced back in 3.5, they had to use a tokenizer hack to get it to work - the parser wasn't powerful enough to handle the problem on its own.

like image 100
user2357112 supports Monica Avatar answered Oct 21 '25 07:10

user2357112 supports Monica