10

I've read about new Python "keywords" async and await. However they are neither really keywords nor reserved in a namespace.

>>> import keyword
>>> keyword.iskeyword("async")
False
>>> async
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'async' is not defined

In the example I would expect True and SyntaxError for a keyword.

So, what exactly is async in Python? How it works?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Thyrst'
  • 2,253
  • 2
  • 22
  • 27
  • `async` only applies in Python 3.5. Is that the version you are using? – Akshat Mahajan Apr 07 '17 at 21:52
  • 6
    `async` and `await` aren't "real" keywords yet, but they will be in Python 3.7. – vaultah Apr 07 '17 at 21:53
  • I use Python 3.6.0 – Thyrst' Apr 07 '17 at 21:53
  • 1
    According to [PEP 492](https://www.python.org/dev/peps/pep-0492/#why-async-def-and-not-def-async) `async` is a *statement qualifier*. – Barmar Apr 07 '17 at 21:55
  • @Thyrst': If you look at the [reference grammar](https://docs.python.org/3.6/reference/grammar.html) for Python 3.6, you'll see that `async` and `await` have no independent identity when defined without a function definition next to it. So they aren't keywords, but the compiler will recognise them if you put a lambda function next to it. – Akshat Mahajan Apr 07 '17 at 21:56
  • Related : [How the heck does async/await work in Python 3.5?](https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/) – VMAtm Apr 08 '17 at 13:53

1 Answers1

10

For backward compatibility purposes, in Python 3.5 and 3.6, async and await are parsed through an ugly tokenizer hack. Inside an async def function definition, or for an async directly before a def, the tokenizer replaces NAME tokens for async and await with ASYNC and AWAIT tokens; in other contexts, the tokenizer emits regular NAME tokens for async and await, treating them as identifiers.

You can see the code that handles it in Parser/tokenizer.c, and you can find the backward compatibility plan in PEP 492, the PEP that introduced async and await syntax.

user2357112
  • 260,549
  • 28
  • 431
  • 505