2.3. 标识符和关键字

标识符 (或者叫做 名称) 由以下词法定义进行描述。

Python 中的标识符语法是基于 Unicode 标准附件 UAX-31,并加入了下文所定义的细化与修改;更多细节还可参见 PEP 3131

在 ASCII 范围内 (U+0001..U+007F),可用于标识符的字符与 Python 2.x 一致: 大写和小写字母 AZ,下划线 _ 以及数字 09,但不可以数字打头。

Python 3.0 引入了 ASCII 范围以外的额外字符 (见 PEP 3131)。这些字符的分类使用包含于 unicodedata 模块中的 Unicode 字符数据库版本。

标识符的长度没有限制。对大小写敏感。

  1. identifier ::= xid_start xid_continue*
  2. id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
  3. id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
  4. xid_start ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
  5. xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">

上文所用 Unicode 类别码的含义:

  • Lu - 大写字母

  • Ll - 小写字母

  • Lt - 词首大写字母

  • Lm - 修饰字母

  • Lo - 其他字母

  • Nl - 字母数字

  • Mn - 非空白标识

  • Mc - 含空白标识

  • Nd - 十进制数字

  • Pc - 连接标点

  • Other_ID_Start - 由 PropList.txt 定义的显式字符列表,用来支持向下兼容

  • Other_ID_Continue - 同上

所有标识符在解析时会被转换为规范形式 NFKC;标识符的比较都是基于 NFKC。

Unicode 4.1 中的所有可用标识符字符列表参见以下非规范 HTML 文件链接 https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html

2.3.1. 关键字

以下标识符被作为语言的保留字或称 关键字,不可被用作普通标识符。关键字的拼写必须与这里列出的完全一致。

  1. False await else import pass
  2. None break except in raise
  3. True class finally is return
  4. and continue for lambda try
  5. as def from nonlocal while
  6. assert del global not with
  7. async elif if or yield

2.3.2. 保留的标识符类

某些标识符类 (除了关键字) 具有特殊的含义。这些标识符类的命名模式是以下划线字符打头和结尾:

  • _*
  • 不会被 from module import * 导入。特殊标识符 在交互式解释器中被用来存放最近一次求值结果;它保存在 builtins 模块中。当不处于交互模式时, 无特殊含义也没有预定义。参见 import 语句

注解

_ 作为名称常用于连接国际化文本;请参看 gettext 模块文档了解有关此约定的详情。

  • *
  • 系统定义的名称。这些名称由解释器及其实现 (包括标准库) 所定义。现有系统定义名称相关讨论参见 特殊方法名称 等章节。未来的 Python 版本中还将定义更多此类名称。任何 不遵循文档指定方式使用 * 名称的行为都可能导致无警告的出错。

  • __*

  • 类的私有名称。这种名称在类定义中使用时,会以一种混合形式重写以避免在基类及派生类的 "私有" 属性之间出现名称冲突。参见 标识符(名称)