You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Python完整关键字列表?keyword.py仅含基础关键字

First off, let's clarify a crucial distinction here—because what you're referring to as "keywords" actually covers a few different categories of built-in Python entities, and that's why keyword.kwlist doesn't include things like len, raw_input, or error names. Let's break this down and show you how to get each full list:

1. What keyword.kwlist actually contains

The kwlist in keyword.py is the complete list of Python's reserved keywords—these are words that are part of the language syntax, so you can't use them as variable names, function names, etc. Examples are if, for, class, def. This list is intentionally small and fixed (with minor changes between Python versions), and it's the definitive source for true keywords.

To double-check if a word is a keyword, you can use the module's helper function:

import keyword
print(keyword.iskeyword('if'))  # Returns True
print(keyword.iskeyword('len'))  # Returns False (it's a built-in function, not a keyword)

2. Getting built-in functions like len and raw_input

Functions like len, raw_input (Python 2; use input in Python 3), and print (a function in Python 3, a keyword in Python 2) are part of Python's built-in namespace. To get the full list of all built-in objects (including functions, types, and exceptions), run this in your Python interpreter:

dir(__builtins__)

If you want to filter just the built-in functions (excluding types and exceptions), you can do something like this:

import types
# Get all names in the built-in namespace
all_builtins = dir(__builtins__)
# Filter to only include function objects
builtin_functions = [name for name in all_builtins if isinstance(getattr(__builtins__, name), types.FunctionType)]
print(builtin_functions)

3. Getting all error/exception names

Error names like ValueError, TypeError, and IndexError are built-in exception classes. To get a list of all of them, you can filter the built-in namespace to include only classes that inherit from BaseException:

# Get all names in the built-in namespace
all_builtins = dir(__builtins__)
# Filter to only include exception classes
builtin_exceptions = [name for name in all_builtins if isinstance(getattr(__builtins__, name), type) and issubclass(getattr(__builtins__, name), BaseException)]
print(builtin_exceptions)

Quick recap

  • True keywords: Use keyword.kwlist (this is the full, official list of syntax-reserved words)
  • Built-in functions/objects: Use dir(__builtins__) (filter as needed)
  • Built-in exceptions: Filter __builtins__ for classes that inherit from BaseException

内容的提问来源于stack exchange,提问作者Doron Sever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:58:51