如何在 python 中为长名称选择合适的变量名称

How to choose proper variable names for long names in python

我需要帮助为实际名称较长的变量选择专有名称。我已经阅读了 pep8 文档,但找不到解决此类问题的方法。

您会将 very_long_variable_name 重命名为 vry_lng_var_nm 之类的名称,还是保持原样。我注意到在库中构建的 python 名称非常短,如果存在这种情况,我想遵循约定。

我知道我可以给它起一个不太具有描述性的名字并添加描述,这将解释它的含义,但你认为变量名称应该是什么。

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
# Notice how the argument name "grade" has a role to play in readability
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)

请注意,在前面的示例中,如何使用 grade 作为参数允许将其从函数名称中删除而不失清晰。

保持简短的范围以便快速查找

在更短的范围内封装逻辑。这样,您就不需要在变量名中提供那么多细节,因为可以在上面的几行中快速查找到。一个经验法则是让你的函数适合你的 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:
    ...

花时间思考可读性

最后但并非最不重要的一点是花时间思考如何使代码更具可读性。这与您花在思考逻辑和代码优化上的时间一样重要。最好的代码是每个人都能阅读的代码,从而每个人都可以改进。