max*_*max 17 python containers coding-style identifier
命名容器时,有什么更好的编码风格:
source = {}
#...
source[record] = some_file
Run Code Online (Sandbox Code Playgroud)
要么
sources = {}
#...
sources[record] = some_file
Run Code Online (Sandbox Code Playgroud)
复数在创作时更自然; 任务中的单数.
这不是一个无所事事的问题; 当我不确定变量是容器还是单个值时,我确实发现自己在旧代码中感到困惑.
UPDATE
看来人们普遍认为,当字典用作映射时,最好使用更详细的名称(例如recordToSourceFilename
); 如果我绝对想要使用短名称,那么将其复数(例如sources
).
Pat*_*ini 16
我认为有两个非常具体的词典用例应该单独识别.但是,在解决它们之前,应该注意字典的变量名应该几乎总是单数,而列表应该几乎总是复数.
字典作为类似对象的实体:有时候你有一个代表某种类似对象的数据结构的字典.在这些实例中,字典几乎总是引用单个类似对象的数据结构,因此应该是单数的.例如:
# 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']
Run Code Online (Sandbox Code Playgroud)字典作为映射实体:其他时候,您的字典可能表现得更像典型的哈希映射.在这种情况下,最好使用更直接的名称,尽管仍然是单数.例如:
# assume that idToUser is a dictionary mapping IDs to user objects
user = idToUser['0001a']
print user.name
Run Code Online (Sandbox Code Playgroud)列表:最后,您有列表,这是一个完全独立的想法.这些应该几乎总是复数,因为它们很简单,是其他实体的集合.例如:
users = [userA, userB, userC] # makes sense
for user in users:
print user.name # especially later, in iteration
Run Code Online (Sandbox Code Playgroud)我确信有一些模糊的或其他不太可能的情况可能会要求在这里做出一些例外,但我觉得这是一个非常强大的指南,在命名字典和列表时要遵循,不仅仅是在Python中,而是在所有语言中.
它应该是复数,因为程序的行为就像你大声朗读一样.让我告诉你为什么它不应该是单数的(完全人为的例子):
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!!
...
Run Code Online (Sandbox Code Playgroud)
此外,有时候最好有一个更明确的名称,你可以从中推断映射(对于字典)和可能的类型.当我引入字典变量时,我通常会添加一个简单的注释.一个例子:
# Customer ID => Customer
idToCustomer = {}
[...]
idToCustomer[1] = Customer(name = "Tony")
Run Code Online (Sandbox Code Playgroud)
我更喜欢复数形式的容器.使用时只有一些可以理解的逻辑:
entries = []
for entry in entries:
#Code...
Run Code Online (Sandbox Code Playgroud)