简体   繁体   中英

How do I put new keywords into the 'keyword' module?

Before this is marked as duplicate, let me clarify. I don't want to define a new keyword. I want to put async and await into the list of keywords so they will be colored as keywords in IDLE.

Since version 3.5, asyncio doesn't need to be imported in order to use async and await (though there are very few circumstances where you wouldn't import asyncio ), so I want them to be colored as keywords. I can't stand seeing async def where def is colored orange but async is the default black.

I looked through colorizer.py in idlelib and, while you can colorize string prefixes and the like via the module itself (I already did this for format strings) but you can't insert new keywords except by editing keywords . When I opened that module, I saw this:

    """...This file is automatically generated; please don't muck it up!

    To update the symbols in this file, 'cd' to the top directory of
    the python source tree after building the interpreter and run:

        ./python Lib/keyword.py
    """

I honestly don't know what is meant by "building the interpreter". Is there a way to alter this process during installation or do I have to edit the C files and run them? Or is there another, easier way?

You could just update that module dynamically .

Create a file you store in your homedirectory with:

import keyword

keyword.kwlist += ['async', 'await']
keyword.iskeyword = frozenset(keyword.kwlist).__contains__

then set the IDLESTARTUP environment variable to point to that file. Now every time IDLE is started with the -s switch, your keyword module is updated to include your desired 'keywords'. If you find the -s switch too cumbersome, you can also move the file to $HOME/.Idle.py to have it loaded unconditionally, or move it to the USER_SITE location to run it for all Python code ; the latter does carry more risk of course.

The warning at the top is otherwise reminding you that the file is generated when building the Python interpreter from source. If you were to edit the file now, on your system, you won't have to worry about that file being replaced. However, if you ever were to upgrade Python, it is likely to be clobbered and you'd have to make the change again.

Note that in Python 3.7, async and await will be actual keywords, so you won't need to wait all that long. In the meantime, you may want to pick a better IDE. I use Sublime Text 3 and Atom, both of which support the MagicPython code highlighter , which already highlights await and async correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM