python 反模式
不使用 pythonic 的循环:
l = [1,2,3]
#Bad
for i in range(0,len(list)):
le = l[i]
print(i,le)
#Good
for i,le in enumerate(l):
print(i,le)
函数调用返回一个以上的变量类型
#Bad
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
return None
return r
res = filter_for_foo(["bar","foo","faz"])
if res is not None:
#continue processing
pass
#Good
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
raise SomeException("critical condition unmet!")
return r
try:
res = filter_for_foo(["bar","foo","faz"])
#continue processing
except SomeException:
#handle exception
循环永不终止
#example:
i = 0
while i < 10:
do_something()
#we forget to increment i
不使用 .iteritems() 遍历 dict 的键/值对.
#Bad
d = {'foo' : 1,'bar' : 2}
for key in d:
value = d[key]
print("%s = %d" % (key,value))
#Good
for key,value in d.iteritems():
print("%s = %d" % (key,value))
不使用 zip() 遍历一对列表
#Bad
l1 = [1,2,3]
l2 = [4,5,6]
for i in range(l1):
l1v = l1[i]
l2v = l2[i]
print(l1v,l2v)
#Good
for l1v,l2v in zip(l1,l2):
print(l1v,l2v)
Using "key in list" to check if a key is contained in a list.
This is not an error but inefficient, since the list search is O(n). If possible, a set or dictionary
should be used instead.
Note: Since the conversion of the list to a set is an O(n) operation, it should ideally be done only once when generating the list.
#Bad:
l = [1,2,3,4]
if 3 in l:
pass
#Good
s = set(l)
if 3 in s:
pass
在循环之后,不使用 'else'.
#Bad
found = False
l = [1,2,3]
for i in l:
if i == 4:
found = True
break
if not found:
#not found...
pass
#Good
for i in l:
if i == 4:
break
else:
#not found...
对于dict,不使用.setdefault()设置初始值
#Bad
d = {}
if not 'foo' in d:
d['foo'] = []
d['foo'].append('bar')
#Good
d = {}
foo = d.setdefault('foo',[])
foo.append(bar)
对于dict,不使用.get()返回缺省值
#Bad
d = {'foo' : 'bar'}
foo = 'default'
if 'foo' in d:
foo = d['foo']
#Good
foo = d.get('foo','default')
使用map/filter而不是列表解析
#Bad:
values = [1,2,3]
doubled_values = map(lambda x:x*2,values)
#Good
doubled_values = [x*2 for x in values]
#Bad
filtered_values = filter(lambda x:True if x < 2 else False,values)
#Good
filtered_values = [x for x in values if x < 2]
不使用defaultdict
#Bad
d = {}
if not 'count' in d:
d['count'] = 0
d['count']+=1
#Good
from collections import defaultdict
d = defaultdict(lambda :0)
d['count']+=1
从一个函数中返回多个值时,不使用命名元组(namedtuple)
命名元组可以用于任何正常元组使用的地方,但可以通过name访问value,而不是索引。这使得代码更详细、更容易阅读。
#Bad
def foo():
#....
return -1,"not found"
status_code,message = foo()
print(status_code,message)
#Good
from collections import namedtuple
def foo():
#...
return_args = namedtuple('return_args',['status_code','message'])
return return_args(-1,"not found")
ra = foo()
print(ra.status_code,ra.message)
不使用序列的显式解包
支持解包的序列有:list, tuple, dict
#Bad
l = [1,"foo","bar"]
l0 = l[0]
l1 = l[1]
l2 = l[2]
#Good
l0,l1,l2 = l
不使用解包一次更新多个值
#Bad
x = 1
y = 2
_t = x
x = y+2
y = x-4
#Good
x = 1
y = 2
x,y = y+2,x-4
不使用'with'打开文件
#Bad
f = open("file.txt","r")
content = f.read()
f.close()
#Good
with open("file.txt","r") as input_file:
content = f.read()
要求许可而不是宽恕
#Bad
import os
if os.path.exists("file.txt"):
os.unlink("file.txt")
#Good
import os
try:
os.unlink("file.txt")
except OSError:
pass
不使用字典解析
#Bad
l = [1,2,3]
d = dict([(n,n*2) for n in l])
#Good
d = {n : n*2 for n in l}
使用字符串连接,而不是格式化
#Bad
n_errors = 10
s = "there were "+str(n_errors)+" errors."
#Good
s = "there were %d errors." % n_errors
变量名包含类型信息(匈牙利命名)
#Bad
intN = 4
strFoo = "bar"
#Good
n = 4
foo = "bar"
实现java风格的getter和setter方法,而不是使用属性。
#Bad
class Foo(object):
def __init__(a):
self._a = a
def get_a(self):
return a
def set_a(self,value):
self._a = value
#Good
class Foo(object):
def __init__(a):
self._a = a
@property
def a(self):
return self._a
@a.setter
def a(self,value):
self._a = value
#Bad
def calculate_with_operator(operator, a, b):
if operator == '+':
return a+b
elif operator == '-':
return a-b
elif operator == '/':
return a/b
elif operator == '*':
return a*b
#Good
def calculate_with_operator(operator, a, b):
possible_operators = {
'+': lambda a,b: a+b,
'-': lambda a,b: a-b,
'*': lambda a,b: a*b,
'/': lambda a,b: a/b
}
return possible_operators[operator](a,b)
#Bad
class DateUtil:
@staticmethod
def from_weekday_to_string(weekday):
nameds_weekdays = {
0: 'Monday',
5: 'Friday'
}
return nameds_weekdays[weekday]
#Good
def from_weekday_to_string(weekday):
nameds_weekdays = {
0: 'Monday',
5: 'Friday'
}
return nameds_weekdays[weekday]
python 反模式的更多相关文章
- Python编程中的反模式
Python是时下最热门的编程语言之一了.简洁而富有表达力的语法,两三行代码往往就能解决十来行C代码才能解决的问题:丰富的标准库和第三方库,大大节约了开发时间,使它成为那些对性能没有严苛要求的开发任务 ...
- ORM 是一种讨厌的反模式
本文由码农网 – 孙腾浩原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! (“Too Long; Didn’t Read.”太长不想看,可以看这段摘要 )ORM是一种讨厌的反模式,违背 ...
- 《SQL 反模式》 学习笔记
第一章 引言 GoF 所著的的<设计模式>,在软件领域引入了"设计模式"(design pattern)的概念. 而后,Andrew Koenig 在 1995 年造了 ...
- 重构24-Remove Arrowhead Antipattern(去掉箭头反模式)
基于c2的wiki条目.Los Techies的Chris Missal同样也些了一篇关于反模式的post. 简单地说,当你使用大量的嵌套条件判断时,形成了箭头型的代码,这就是箭头反模式(arrow ...
- Apache Hadoop最佳实践和反模式
摘要:本文介绍了在Apache Hadoop上运行应用程序的最佳实践,实际上,我们引入了网格模式(Grid Pattern)的概念,它和设计模式类似,它代表运行在网格(Grid)上的应用程序的可复用解 ...
- 开发反模式 - SQL注入
一.目标:编写SQL动态查询 SQL常常和程序代码一起使用.我们通常所说的SQL动态查询,是指将程序中的变量和基本SQL语句拼接成一个完整的查询语句. string sql = SELECT * FR ...
- 开发反模式(GUID) - 伪键洁癖
一.目标:整理数据 有的人有强迫症,他们会为一系列数据的断档而抓狂. 一方面,Id为3这一行确实发生过一些事情,为什么这个查询不返回Id为3的这一行?这条记录数据丢失了吗?那个Column到底是什么? ...
- 查询反模式 - 正视NULL值
一.提出问题 不可避免地,我们都数据库总有一些字段是没有值的.不管是插入一个不完整的行,还是有些列可以合法地拥有一些无效值.SQL 支持一个特殊的空值,就是NULL. 在很多时候,NULL值导致我们的 ...
- Python教程(1.2)——Python交互模式
上一节已经说过,安装完Python,在命令行输入"python"之后,如果成功,会得到类似于下面的窗口: 可以看到,结尾有3个>符号(>>>).>&g ...
随机推荐
- 【原】UIView实现点击着重效果的解决方案
我们知道,在IOS中UIButton UIControl都有一个默认的选中效果,即点中后会图标会变暗,移开后又恢复正常.如何让UIView UIImageView等这些普通的view也实现同样的效果呢 ...
- 分享到QQ空间、新浪微博、腾讯微博的代码
今天公司原来的分享代码,在IE下有问题.网上找了下网上的分享代码. 给网页加上分享代码,借助网友的力量推广网站,目前已经很流行了 以下是网页代码 QQ空间分享代码如下: <a href=&quo ...
- 利用eclipse抽取 代码片段为方法
选取要被抽取成方法的代码片段,右键->Refactor--->Extract Method 填写方法名称 抽取后成了这个样子:
- javascript之工厂方式定义对象
每一个函数对象都有一个length属性,表示该函数期望接收的参数个数. <html> <head> <script type="text/javascript& ...
- virtualbox 安装 虚拟机的时候报错不能创建新任务
找到原因是因为自己的windows是破解的, 找到C:\Windows\system32\uxtheme.dll这个文件,我的破解的windows在这里自带了一个uxtheme.dll.backup的 ...
- JavaScript闭包的底层运行机制
转自:http://blog.leapoahead.com/2015/09/15/js-closure/ 我研究JavaScript闭包(closure)已经有一段时间了.我之前只是学会了如何使用它们 ...
- CSS中vw和vh单位的使用
vw——viewpoint width,视窗宽度,1vw等于视窗宽度的1%: vh——viewpoint height,视窗高度,1vh等于视窗高度的1%:例子:http://tutorialzine ...
- Spring学习笔记之 Spring IOC容器(二) 之注入参数值,自动组件扫描方式,控制Bean实例化方式,使用注解方式
本节主要内容: 1. 给MessageBean注入参数值 2. 测试Spring自动组件扫描方式 3. 如何控制ExampleBean实例化方式 4. 使用注解方式重构Jdb ...
- 设计模式C#实现(六)——单例模式
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点. 构成: 1.私有的构造函数 2.私有静态的实例 3.返回实例的静态方法 public class Singleton { privat ...
- Less里css表达式的写法
项目中用的grunt-contrib-less, 写了以下less代码 .mapfix{ position: fixed; top:10px; width: 430px; z-index: 100; ...