Python风格

Osc*_*Ryz 3 python coding-style

简单的初学者问题:

我已经创建了一个小的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  )
Run Code Online (Sandbox Code Playgroud)

要么

shutil.copyfile( remote 
                     if( filecmp.cmp(local, config_file ) ) 
                     else local,
                 config_file  )
Run Code Online (Sandbox Code Playgroud)

要么

tocopy = remote if( filecmp.cmp( local, config_file ) ) else local 
shutil.copyfile( tocopy, config_file )
Run Code Online (Sandbox Code Playgroud)

或者是什么?

另外,对于多字名称在python中命名var的优先方法是什么,是"to_copy","tocopy","toCopy","ToCopy"

谢谢.

Gre*_*ill 17

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

if filecmp.cmp(local, config_file):
    shutil.copyfile(remote, config_file)
else:
    shutil.copyfile(local, config_file)
Run Code Online (Sandbox Code Playgroud)

y if x else z在这种情况下几乎不需要使用内联,因为周围的代码足够简单.


Pat*_*ton 6

Python风格指南:

关于列出复合表达式:

通常不鼓励使用复合语句(同一行上的多个语句).

是:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()
Run Code Online (Sandbox Code Playgroud)

或者对于你提供的代码,Greg的例子很好:

if filecmp.cmp(local, config_file):
    shutil.copyfile(remote, config_file)
else:
    shutil.copyfile(local, config_file)
Run Code Online (Sandbox Code Playgroud)

而不是:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
Run Code Online (Sandbox Code Playgroud)

方法名称和实例变量

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

更新:根据奥斯卡的要求,还列出了他的代码如何以这种方式看待.


Vin*_*vic 5

我见过的最常见的命名是下划线分隔的单词 to_copy。

至于格式风格,我没看到有这样的约定。我发现

source = remote if filecmp.cmp(local, config_file) else local

shutil.copyfile(source, config_file)
Run Code Online (Sandbox Code Playgroud)

成为您选择中最清楚的。

并且看到每个人都更喜欢拆分 if Id,至少,封装 copyfile 调用,以防您有一天希望更改它:

def copy_to(source, destination):
    shutil.copyfile(source,destination)

if filecmp.cmp(local, config_file):
    copy_to(remote, config_file)
else:
    copy_to(local, config_file)
Run Code Online (Sandbox Code Playgroud)


Tim*_*her 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)
Run Code Online (Sandbox Code Playgroud)