background image

为什么会有字符数的限制

也许在

Python 编码风格指导(PEP8)中最有争议的一部分要数每行代码不超过 80 个字符

的限制。没错,实际上是

79 个字符,但我使用 80 个字符,这个大概数,它是给程序员的一

个参考值。

   古老的 VT100 终端   现在很多软件公司采用的编码规范基本是 PEP8,

但每行

80 个字符的限制除外。GitHub 上的项目,大多数都遵循 PEP8 规范(这一点似乎达到

了高度的统一

),但遵守 80 个字符限制的很少。在一些有明确规定的规范标准中,这个限制

可能会增加

(100 或 120),甚至完全删除。这样做常长见的理由是:我们已经不是使用

VT100 终端编程的年代了,我们有了更大,更高分辨率的屏幕。这是事实,但我发现,在
Python 编码中采用这个 80 个字符的规范,配合空格的使用,这会让我们的代码更急凑,更
可读。

   有一点你可以看出,在自然情况下,Python 语句的长度一般会占大概 35-60 个字

(不包括缩进)。更长的语句很少见。如果突然有一个句子比其它的要长很多,会显得很突

兀,不好看。同样,使用强制性的空格来增加行宽能够从视觉上帮助你优化减少嵌套循环的
层数,一般的建议是重构代码不要让缩进多于

4 层。   

例如,把下面这个:

    

def  search(directory,  file_pattern,  path_match,      follow_symlinks=True,  output=True, 
colored=True):   ''' Search the files matching the pattern. The files will be returned, and can be 
optionally  printed  '''      pattern  =  re.compile(file_pattern)      results  =  []      for  root, 
sub_folders,  files  in  os.walk(directory,  followlinks=follow_symlinks):      #  Ignore  hidden 
directories   if '/.' in root:   continue   # Search in files and subfolders   for filename 
in  files  +  sub_folders:      full_filename  =  os.path.join(root,  filename)      to_match  = 
full_filename  if  path_match  else  filename      match  =  re.search(pattern,  to_match)      if 
match:      #  Split  the  match  to  be  able  to  colorize  it      #  prefix,  matched_pattern,  sufix 
smatch 

[to_match[:match.start()], 

to_match[match.start(): 

match.end()], 

to_match[match.end():]]      if  not  path_match:      #  Add  the  fullpath  to  the  prefix 
smatch[0]  =  os.path.join(root,  smatch[0])      if  output:      print_match(smatch,  colored) 
results.append(full_filename)   return results    

和这个比较:

   def search(directory, file_pattern, path_match,    follow_symlinks=True, 

output=True, colored=True):    ''' Search the files matching the pattern.    The files will be 
returned, and can be optionally printed '''    pattern = re.compile(file_pattern)    results = [] 
for root, sub_folders, files in os.walk(directory,   followlinks=follow_symlinks):   # Ignore 
hidden directories   if '/.' in root:   continue   # Search in files and subfolders   for 
filename in files + sub_folders:   full_filename = os.path.join(root, filename)   to_match = 
full_filename  if  path_match  else  filename      match  =  re.search(pattern,  to_match)      if