因为您使用的是python3.4,所以我建议用IntEnum替换所有的幻数。在
这将使您的代码更易于理解,并在必要时更易于修改。在
使用枚举的一个好处是,您不会像处理变量那样意外地更改它们的值。在
考虑这一准则import os
from hashlib import sha256
def compare(src, dest):
"""
Compare two files.
Arguments
src: Path of the source file.
dest: Path of the destination file.
Returns:
0 if source and destination are different
1 source and destination are identical
2 destination doesn't exist
3 source doesn't exist
"""
xsrc, xdest = os.path.exists(src), os.path.exists(dest)
if not xsrc:
return 3
if not xdest:
return 2
with open(src, 'rb') as s:
csrc = sha256(s.read()).digest()
if xdest:
with open(dest, 'rb') as d:
cdest = sha256(d.read()).digest()
else:
cdest = b''
if csrc == cdest:
return 1
return 2
这个代码本身并不清楚。它被记录下来。
但是一旦您尝试使用返回值,您就必须不断地引用文档。在
你能告诉我为什么下面的代码会这么做吗?如果没有参考compare的文档,就不能这样做。在
^{pr2}$
现在看看这个import os
from hashlib import sha256
from enum import IntEnum
class Cmp(IntEnum):
differ = 0 # source and destination are different
same = 1 # source and destination are identical
nodest = 2 # destination doesn't exist
nosrc = 3 # source doesn't exist
def compare(src, dest):
"""
Compare two files.
Arguments
src: Path of the source file.
dest: Path of the destination file.
Returns:
Cmp enum
"""
xsrc, xdest = os.path.exists(src), os.path.exists(dest)
if not xsrc:
return Cmp.nosrc
if not xdest:
return Cmp.nodest
with open(src, 'rb') as s:
csrc = sha256(s.read()).digest()
if xdest:
with open(dest, 'rb') as d:
cdest = sha256(d.read()).digest()
else:
cdest = b''
if csrc == cdest:
return Cmp.same
return Cmp.differ
所以如果你现在尝试使用它,它看起来像这样
^{4}$
您不需要参考compare的文档就可以理解这一点。您甚至不必检查Cmp枚举的细节。在