Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> import keyword
>>> keyword.iskeyword('type')
False

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading