我需要帮助为具有长实际名称的变量选择适当的名称。我读过pep8文档,但我找不到解决这个问题。
您会将very_long_variable_name
重命名为vry_lng_var_nm
,还是将其保留原样。我注意到库中的pythons构建的名称很短,如果存在这种情况,我想遵循这些约定。
我知道我可以将其命名为非描述性的东西并添加描述,这可以解释其含义,但您认为应该是变量名称。
答案 0 :(得分:17)
PEP8建议使用短变量名称,但要实现这一点需要良好的编程卫生。以下是保持变量名称简短的一些建议。
首先,不要将变量名称视为其内容的完整描述符。名称应该清楚,主要是为了跟踪它们来自何处,然后才能对内容进行一些说明。
# This is very descriptive, but we can infer that by looking at the expression
students_with_grades_above_90 = filter(lambda s: s.grade > 90, students)
# This is short and still allows the reader to infer what the value was
good_students = filter(lambda s: s.grade > 90, students)
使用注释和文档字符串来描述正在发生的事情,而不是变量名称。
# We feel we need a long variable description because the function is not documented
def get_good_students(students):
return filter(lambda s: s.grade > 90, students)
students_with_grades_above_90 = get_good_students(students)
# If the reader is not sure about what get_good_students returns,
# their reflex should be to look at the function docstring
def get_good_students(students):
"""Return students with grade above 90"""
return filter(lambda s: s.grade > 90, students)
# You can optionally comment here that good_students are the ones with grade > 90
good_students = get_good_students(students)
如果您觉得某个函数需要一个非常具体的名称,那么该函数本身可能过于具体。
# Very long name because very specific behaviour
def get_students_with_grade_above_90(students):
return filter(lambda s: s.grade > 90, students)
# Adding a level of abstraction shortens our method name here
def get_students_above(grade, students):
return filter(lambda s: s.grade > grade, students)
# What we mean here is very clear and the code is reusable
good_students = get_students_above(90, students)
最后,将逻辑封装在较短的范围内。这样,您就不需要在变量名中提供那么多细节,因为它可以快速查找上面几行。一个经验法则是让你的函数适合你的IDE,而不用滚动,如果你超越它,就将一些逻辑封装在新函数中。
# line 6
names = ['John', 'Jane']
... # Hundreds of lines of code
# line 371
# Wait what was names again?
if 'Kath' in names:
...
在这里,我忘记了names
的内容,向上滚动会让我失去更多的追踪。这样更好:
# line 6
names = ['John', 'Jane']
# I encapsulate part of the logic in another function to keep scope short
x = some_function()
y = maybe_a_second_function(x)
# line 13
# Sure I can lookup names, it is right above
if 'Kath' in names:
...
最后但并非最不重要的是花时间思考如何使代码更具可读性。这与您考虑逻辑和代码优化的时间一样重要。最好的代码是每个人都可以阅读的代码,因此每个人都可以改进。