什么是好的Python格式风格

2 投票
5 回答
1454 浏览
提问于 2025-04-11 18:56

我写了一个小的Python脚本,用来在我测试的两个文件之间切换。

我想问一下,下面这段代码用什么样的Python格式风格比较好:

import filecmp
import shutil

local = "local.txt"
remote = "remote.txt"
config_file = "C:\some\path\file.txt"

shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file  )

或者

shutil.copyfile( remote 
                     if( filecmp.cmp(local, config_file ) ) 
                     else local,
                 config_file  )

或者

tocopy = remote if( filecmp.cmp( local, config_file ) ) else local 
shutil.copyfile( tocopy, config_file )

那还有其他的选择吗?

另外,Python中对于多个单词组成的变量名,哪种命名方式更好呢?是用“to_copy”,还是“tocopy”,或者“toCopy”,还有“ToCopy”呢?

5 个回答

5

我觉得第三种选择看起来最自然,不过你在括号里使用空格和多余的括号,这和Python的风格指南是相悖的。

那个指南也回答了关于to_copy的问题,但我可能会用更清晰的名字。

我会这样写:

import filecmp
import shutil

local = "local.txt"
remote = "remote.txt"

destination = r"C:\some\path\file.txt"
source = remote if filecmp.cmp(local, destination) else local

shutil.copyfile(source, destination)
5

来自Python风格指南的内容:

关于复合表达式的书写:

复合语句(在同一行上写多个语句)通常是不推荐的。

可以这样写:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

或者你提供的代码,Greg的例子是个不错的选择:

if filecmp.cmp(local, config_file):
    shutil.copyfile(remote, config_file)
else:
    shutil.copyfile(local, config_file)

最好不要这样写:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

方法名称和实例变量

使用函数命名规则:小写字母,必要时用下划线分隔单词,以提高可读性。

更新:根据Oscar的要求,也列出了他代码的这种写法。

16

对于这个条件语句,我可能会选择:

if filecmp.cmp(local, config_file):
    shutil.copyfile(remote, config_file)
else:
    shutil.copyfile(local, config_file)

在这种情况下,使用这种写法 y if x else z 就没必要了,因为周围的代码已经简单到不需要这样做。

撰写回答