字典使用单数还是复数标识符?
在给一个容器命名的时候,哪种命名风格更好呢:
source = {}
#...
source[record] = some_file
或者
sources = {}
#...
sources[record] = some_file
在创建的时候用复数形式更自然,而在赋值的时候用单数形式更合适。
这个问题并不是随便问的;我自己在看旧代码的时候就曾经搞混过,不知道一个变量是个容器还是一个单独的值。
更新
看起来大家普遍认为,当字典用作映射的时候,最好用更详细的名字(比如 recordToSourceFilename
);如果我真的想用一个短名字,那就用复数形式(比如 sources
)。
3 个回答
5
我更喜欢用复数形式来表示容器。使用复数形式有一种很容易理解的逻辑:
entries = []
for entry in entries:
#Code...
6
这里应该用复数形式,因为这样程序的表现就和你大声读出来的一样。让我给你举个例子,说明为什么不应该用单数形式(这个例子有点牵强):
c = Customer(name = "Tony")
c.persist()
[...]
#
# 500 LOC later, you retrieve the customer list as a mapping from
# customer ID to Customer instance.
#
# Singular
customer = fetchCustomerList()
nameOfFirstCustomer = customer[0].name
for c in customer: # obviously it's totally confusing once you iterate
...
# Plural
customers = fetchCustomerList()
nameOfFirstCustomer = customers[0].name
for customer in customers: # yeah, that makes sense!!
...
此外,有时候使用更明确的名称也是个好主意,这样你可以更容易地推断出字典的映射关系和类型。我通常在引入字典变量时加一个简单的注释。举个例子:
# Customer ID => Customer
idToCustomer = {}
[...]
idToCustomer[1] = Customer(name = "Tony")
21
我觉得字典有两种非常具体的使用情况,应该单独提出来。不过,在讨论它们之前,先说一下,字典的变量名通常应该用单数,而列表的变量名则应该用复数。
字典作为类似对象的实体:有时候,你会有一个字典,它代表某种像对象一样的数据结构。在这种情况下,字典几乎总是指代一个单一的对象数据结构,所以应该用单数。例如:
# assume that users is a list of users parsed from some JSON source # assume that each user is a dictionary, containing information about that user for user in users: print user['name']
字典作为映射实体:有时候,你的字典可能更像一个典型的哈希表。在这种情况下,最好用一个更直接的名字,虽然仍然是单数。例如:
# assume that idToUser is a dictionary mapping IDs to user objects user = idToUser['0001a'] print user.name
列表:最后,你有列表,这是一个完全不同的概念。列表几乎总是应该用复数,因为它们只是其他实体的集合。例如:
users = [userA, userB, userC] # makes sense for user in users: print user.name # especially later, in iteration
我相信可能会有一些不常见的情况需要例外,但我觉得在命名字典和列表时,这个原则是相当可靠的,不仅适用于Python,也适用于所有编程语言。