网站建设厌倦,fontawesome wordpress,重庆市造价工程新希望官网,常用网站缩略图自定义总第 113 篇文章#xff0c;本文大约 8000 字#xff0c;阅读大约需要 20 分钟原文#xff1a;https://github.com/zedr/clean-code-pythonpython 版的代码整洁之道。目录如下所示#xff1a;介绍变量函数1. 介绍软件工程的原则#xff0c;来自 Robert C. Martins 的书--《… 总第 113 篇文章本文大约 8000 字阅读大约需要 20 分钟原文https://github.com/zedr/clean-code-pythonpython 版的代码整洁之道。目录如下所示介绍变量函数1. 介绍软件工程的原则来自 Robert C. Martins 的书--《Clean Code》而本文则是适用于 Python 版本的 clean code。这并不是一个风格指导而是指导如何写出可读、可用以及可重构的 pyhton 代码。并不是这里介绍的每个原则都必须严格遵守甚至只有很少部分会得到普遍的赞同。下面介绍的都只是指导而已但这都是来自有多年编程经验的 《Clean Code》的作者。这里的 python 版本是 3.72. 变量2.1 采用有意义和可解释的变量名糟糕的写法ymdstr datetime.date.today().strftime(%y-%m-%d)
好的写法current_date: str datetime.date.today().strftime(%y-%m-%d)
2.2 对相同类型的变量使用相同的词汇糟糕的写法这里对有相同下划线的实体采用三个不同的名字get_user_info()
get_client_data()
get_customer_record()
好的写法如果实体是相同的对于使用的函数应该保持一致get_user_info()
get_user_data()
get_user_record()
更好的写法python 是一个面向对象的编程语言所以可以将相同实体的函数都放在类中作为实例属性或者是方法class User:info : strpropertydef data(self) - dict:# ...def get_record(self) - Union[Record, None]:# ...
2.3 采用可以搜索的名字我们通常都是看的代码多于写过的代码所以让我们写的代码是可读而且可以搜索的是非常重要的如果不声明一些有意义的变量会让我们的程序变得难以理解例子如下所示。糟糕的写法# 86400 表示什么呢
time.sleep(86400)
好的写法# 声明了一个全局变量
SECONDS_IN_A_DAY 60 * 60 * 24time.sleep(SECONDS_IN_A_DAY)
2.4 采用带解释的变量糟糕的写法address One Infinite Loop, Cupertino 95014
city_zip_code_regex r^[^,\\][,\\\s](.?)\s*(\d{5})?$
matches re.match(city_zip_code_regex, address)save_city_zip_code(matches[1], matches[2])
还行的写法这个更好一点但还是很依赖于正则表达式address One Infinite Loop, Cupertino 95014
city_zip_code_regex r^[^,\\][,\\\s](.?)\s*(\d{5})?$
matches re.match(city_zip_code_regex, address)city, zip_code matches.groups()
save_city_zip_code(city, zip_code)
好的写法通过子模式命名来减少对正则表达式的依赖address One Infinite Loop, Cupertino 95014
city_zip_code_regex r^[^,\\][,\\\s](?Pcity.?)\s*(?Pzip_code\d{5})?$
matches re.match(city_zip_code_regex, address)save_city_zip_code(matches[city], matches[zip_code])
2.5 避免让读者进行猜测不要让读者需要联想才可以知道变量名的意思显式比隐式更好。糟糕的写法seq (Austin, New York, San Francisco)for item in seq:do_stuff()do_some_other_stuff()# ...# item 是表示什么dispatch(item)
好的写法locations (Austin, New York, San Francisco)for location in locations:do_stuff()do_some_other_stuff()# ...dispatch(location)
2.6 不需要添加额外的上下文如果类或者对象名称已经提供一些信息来不需要在变量中重复。糟糕的写法class Car:car_make: strcar_model: strcar_color: str
好的写法class Car:make: strmodel: strcolor: str
2.7 采用默认参数而不是条件语句糟糕的写法def create_micro_brewery(name):name Hipster Brew Co. if name is None else nameslug hashlib.sha1(name.encode()).hexdigest()# etc.
这个写法是可以直接给 name 参数设置一个默认数值而不需要采用一个条件语句来进行判断的。好的写法def create_micro_brewery(name: str Hipster Brew Co.):slug hashlib.sha1(name.encode()).hexdigest()# etc.
3. 函数3.1 函数参数2个或者更少限制函数的参数个数是很重要的这有利于测试你编写的函数代码。超过3个以上的函数参数会导致测试组合爆炸的情况也就是需要考虑很多种不同的测试例子。没有参数是最理想的情况。一到两个参数也是很好的三个参数应该尽量避免。如果多于 3 个那么应该需要好好整理函数。通常如果函数多于2个参数那代表你的函数可能要实现的东西非常多。此外很多时候一个高级对象也是可以用作一个参数使用。糟糕的写法def create_menu(title, body, button_text, cancellable):# ...
很好的写法class Menu:def __init__(self, config: dict):title config[title]body config[body]# ...menu Menu({title: My Menu,body: Something about my menu,button_text: OK,cancellable: False}
)
另一种很好的写法class MenuConfig:A configuration for the Menu.Attributes:title: The title of the Menu.body: The body of the Menu.button_text: The text for the button label.cancellable: Can it be cancelled?title: strbody: strbutton_text: strcancellable: bool Falsedef create_menu(config: MenuConfig):title config.titlebody config.body# ...config MenuConfig
config.title My delicious menu
config.body A description of the various items on the menu
config.button_text Order now!
# The instance attribute overrides the default class attribute.
config.cancellable Truecreate_menu(config)
优秀的写法from typing import NamedTupleclass MenuConfig(NamedTuple):A configuration for the Menu.Attributes:title: The title of the Menu.body: The body of the Menu.button_text: The text for the button label.cancellable: Can it be cancelled?title: strbody: strbutton_text: strcancellable: bool Falsedef create_menu(config: MenuConfig):title, body, button_text, cancellable config# ...create_menu(MenuConfig(titleMy delicious menu,bodyA description of the various items on the menu,button_textOrder now!)
)
更优秀的写法rom dataclasses import astuple, dataclassdataclass
class MenuConfig:A configuration for the Menu.Attributes:title: The title of the Menu.body: The body of the Menu.button_text: The text for the button label.cancellable: Can it be cancelled?title: strbody: strbutton_text: strcancellable: bool Falsedef create_menu(config: MenuConfig):title, body, button_text, cancellable astuple(config)# ...create_menu(MenuConfig(titleMy delicious menu,bodyA description of the various items on the menu,button_textOrder now!)
)
3.2 函数应该只完成一个功能这是目前为止软件工程里最重要的一个规则。函数如果完成多个功能就很难对这个函数解耦、测试。如果可以对一个函数分离为仅仅一个动作那么该函数可以很容易进行重构并且代码也方便阅读。即便你仅仅遵守这一点建议你也会比很多开发者更加优秀。糟糕的写法def email_clients(clients: List[Client]):Filter active clients and send them an email.筛选活跃的客户并发邮件给他们for client in clients:if client.active:email(client)
好的写法def get_active_clients(clients: List[Client]) - List[Client]:Filter active clients.return [client for client in clients if client.active]def email_clients(clients: List[Client, ...]) - None:Send an email to a given list of clients.for client in clients:email(client)
这里其实是可以使用生成器来改进函数的写法。更好的写法def active_clients(clients: List[Client]) - Generator[Client]:Only active clients.return (client for client in clients if client.active)def email_client(clients: Iterator[Client]) - None:Send an email to a given list of clients.for client in clients:email(client)
3.3 函数的命名应该表明函数的功能糟糕的写法class Email:def handle(self) - None:# Do something...message Email()
# What is this supposed to do again?
# 这个函数是需要做什么呢
message.handle()
好的写法class Email:def send(self) - None:Send this message.message Email()
message.send()
3.4 函数应该只有一层抽象如果函数包含多于一层的抽象那通常就是函数实现的功能太多了应该把函数分解成多个函数来保证可重复使用以及更容易进行测试。糟糕的写法def parse_better_js_alternative(code: str) - None:regexes [# ...]statements regexes.split()tokens []for regex in regexes:for statement in statements:# ...ast []for token in tokens:# Lex.for node in ast:# Parse.
好的写法REGEXES (# ...
)def parse_better_js_alternative(code: str) - None:tokens tokenize(code)syntax_tree parse(tokens)for node in syntax_tree:# Parse.def tokenize(code: str) - list:statements code.split()tokens []for regex in REGEXES:for statement in statements:# Append the statement to tokens.return tokensdef parse(tokens: list) - list:syntax_tree []for token in tokens:# Append the parsed token to the syntax tree.return syntax_tree
3.5 不要将标志作为函数参数标志表示函数实现的功能不只是一个但函数应该仅做一件事情所以如果需要标志就将多写一个函数吧。糟糕的写法from pathlib import Pathdef create_file(name: str, temp: bool) - None:if temp:Path(./temp/ name).touch()else:Path(name).touch()
好的写法from pathlib import Pathdef create_file(name: str) - None:Path(name).touch()def create_temp_file(name: str) - None:Path(./temp/ name).touch()
3.6 避免函数的副作用函数产生副作用的情况是在它做的事情不只是输入一个数值返回其他数值这样一件事情。比如说副作用可能是将数据写入文件修改全局变量或者意外的将你所有的钱都写给一个陌生人。不过有时候必须在程序中产生副作用--比如刚刚提到的例子必须写入数据到文件中。这种情况下你应该尽量集中和指示产生这些副作用的函数比如说保证只有一个函数会产生将数据写到某个特定文件中而不是多个函数或者类都可以做到。这条建议的主要意思是避免常见的陷阱比如分析对象之间的状态的时候没有任何结构使用可以被任何数据修改的可修改数据类型或者使用类的实例对象不集中副作用影响等等。如果你可以做到这条建议你会比很多开发者都开心。糟糕的写法# This is a module-level name.
# Its good practice to define these as immutable values, such as a string.
# However...
name Ryan McDermottdef split_into_first_and_last_name() - None:# The use of the global keyword here is changing the meaning of the# the following line. This function is now mutating the module-level# state and introducing a side-effect!# 这里采用了全局变量并且函数的作用就是修改全局变量其副作用就是修改了全局变量# 第二次调用函数的结果就会和第一次调用不一样了。global namename name.split()split_into_first_and_last_name()print(name) # [Ryan, McDermott]# OK. It worked the first time, but what will happen if we call the
# function again?
好的写法def split_into_first_and_last_name(name: str) - list:return name.split()name Ryan McDermott
new_name split_into_first_and_last_name(name)print(name) # Ryan McDermott
print(new_name) # [Ryan, McDermott]
另一个好的写法from dataclasses import dataclassdataclass
class Person:name: strpropertydef name_as_first_and_last(self) - list:return self.name.split() # The reason why we create instances of classes is to manage state!
person Person(Ryan McDermott)
print(person.name) # Ryan McDermott
print(person.name_as_first_and_last) # [Ryan, McDermott]
总结原文的目录实际还有三个部分对象和数据结构类单一职责原则Single Responsibility Principle, SRP)开放封闭原则Open/Closed principleOCP里氏替换原则Liskov Substitution Principle LSP)接口隔离原则Interface Segregation Principle ISP)依赖倒置原则Dependency Inversion Principle DIP)不要重复不过作者目前都还没有更新所以想了解这部分内容的建议可以直接阅读《代码整洁之道》对应的这部分内容了。精选文章几个有趣的python技巧10个高效的pandas技巧Mac 下安装配置 Python 开发环境只需几行代码即可实现多线程和多进程操作[Python技巧]如何加快循环操作和Numpy数组运算速度欢迎关注我的微信公众号--算法猿的成长或者扫描下方的二维码大家一起交流学习和进步如果觉得不错在看、转发就是对小编的一个支持