接受与关键字/标准库冲突的变量名约定
Accepted convention for variable names clashing with keywords / standard libs
我有一个函数,我将 datetime.date
和 time
对象作为参数。假设我还想要一个需要命名为 break
或类似名称的参数。我显然不能在不抛出 SyntaxError
的情况下将 break
用作 arg。
为了避免与标准 Python 库名称或关键字发生冲突,最广为接受的重命名约定是什么?
根据 the style guide:
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
具体来说,对于参数:
If a function argument's name clashes with a reserved keyword, it is
generally better to append a single trailing underscore rather than
use an abbreviation or spelling corruption. Thus class_
is better
than clss
. (Perhaps better is to avoid such clashes by using a
synonym.)
和属性名称:
- If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is
preferable to an abbreviation or corrupted spelling. (However,
notwithstanding this rule,
cls
is the preferred spelling for any
variable or argument which is known to be a class, especially the
first argument to a class method.)
我有一个函数,我将 datetime.date
和 time
对象作为参数。假设我还想要一个需要命名为 break
或类似名称的参数。我显然不能在不抛出 SyntaxError
的情况下将 break
用作 arg。
为了避免与标准 Python 库名称或关键字发生冲突,最广为接受的重命名约定是什么?
根据 the style guide:
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.Tkinter.Toplevel(master, class_='ClassName')
具体来说,对于参数:
If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus
class_
is better thanclss
. (Perhaps better is to avoid such clashes by using a synonym.)
和属性名称:
- If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule,
cls
is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)