Python 中 SQL 列的命名风格

Naming style for SQL columns in Python

数据库中的主键通常命名为 "id",这在使用 SQLAlchemy 等工具在 Python:

中构建数据库布局时会出现问题
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer

Base = declarative_base()

class User(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)

显然,这会覆盖内置函数 id. Ok, it is only overwritten in that very small scope of attribute references, however, I might need id in there. The other problem is that syntax highlighting tools treat the name "id" as a function and highlight it accordingly, regardless of the context. This can prominently be seen in SQL-Alchemy's tutorials。第三个,就是感觉脏。

解决这个问题的一个天真的方法是让语法突出显示意识到特殊的上下文。但是,这不是解决方案,因为它只是掩盖了原来的问题,因此可能会导致进一步的问题。

这让我假设重命名可能是一个可能的解决方案。如果我将主键重命名为 user_id 之类的东西,肯定会出现我必须键入

的情况
current_user = User('Peter')
print(current_user.user_id)

current_user.user_id 对我来说看起来和感觉起来非常多余和麻烦。这是因为我从上下文中知道 current_user 实际上是 User 的一个实例。通常,查询哪个 table 以及如何将结果分配给的名称变量都无关紧要。因此,在 Xxx 的 class 变量前面加上 "xxx_" 显然是对由其他问题引起的症状的补救措施,因此不是一个好的解决方案。

其他可能性是在 "id" 之前或添加下划线。但是,前置也不是一种选择,因为它会干扰 Python 对 non-public API parts 的转换。因此,从我的角度来看,以下是可用的最佳解决方案:

class User(Base):
    id_ = Column(Integer, primary_key=True)
    name = Column(String)

但是,我是数据库的新手,我不知道这些问题在实践中是如何解决的,或者这是否被认为是一个问题。所以,我的问题是:

如何在使用 SQLAlchemy 和 Python3 声明的类似 SQL 的数据库中命名 tables 的主键,以便内置id 不会被覆盖,并且在生成的代码中有最小的冗余和混淆。

PEP 8 说:

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

Tkinter.Toplevel(master, class_='ClassName')

所以使用id_就可以了。

然而,由于 id 实际上不是一个关键字,只是一个内置函数,使用 id 也可以,只要它不会导致遮蔽问题id 函数。

另一方面,命名函数参数或变量 class 将是一个语法错误,这就是约定存在的原因。