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?

6
  • async only applies in Python 3.5. Is that the version you are using? Commented Apr 7, 2017 at 21:52
  • 6
    async and await aren't "real" keywords yet, but they will be in Python 3.7. Commented Apr 7, 2017 at 21:53
  • I use Python 3.6.0 Commented Apr 7, 2017 at 21:53
  • 1
    According to PEP 492 async is a statement qualifier. Commented Apr 7, 2017 at 21:55
  • @Thyrst': If you look at the reference grammar 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. Commented Apr 7, 2017 at 21:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.