如何在python中为长名称选择正确的变量名

问题描述 投票:8回答:1

我需要帮助为实际名称较长的变量选择合适的名称。我已经阅读了pep8文档,但找不到该问题。

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

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

python pep8
1个回答
22
投票

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)

注意,在前面的示例中,如何将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:
    ...

花时间考虑可读性

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

© www.soinside.com 2019 - 2024. All rights reserved.