不使用 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 反模式的更多相关文章

  1. Python编程中的反模式

    Python是时下最热门的编程语言之一了.简洁而富有表达力的语法,两三行代码往往就能解决十来行C代码才能解决的问题:丰富的标准库和第三方库,大大节约了开发时间,使它成为那些对性能没有严苛要求的开发任务 ...

  2. ORM 是一种讨厌的反模式

    本文由码农网 – 孙腾浩原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! (“Too Long; Didn’t Read.”太长不想看,可以看这段摘要 )ORM是一种讨厌的反模式,违背 ...

  3. 《SQL 反模式》 学习笔记

    第一章 引言 GoF 所著的的<设计模式>,在软件领域引入了"设计模式"(design pattern)的概念. 而后,Andrew Koenig 在 1995 年造了 ...

  4. 重构24-Remove Arrowhead Antipattern(去掉箭头反模式)

    基于c2的wiki条目.Los Techies的Chris Missal同样也些了一篇关于反模式的post.  简单地说,当你使用大量的嵌套条件判断时,形成了箭头型的代码,这就是箭头反模式(arrow ...

  5. Apache Hadoop最佳实践和反模式

    摘要:本文介绍了在Apache Hadoop上运行应用程序的最佳实践,实际上,我们引入了网格模式(Grid Pattern)的概念,它和设计模式类似,它代表运行在网格(Grid)上的应用程序的可复用解 ...

  6. 开发反模式 - SQL注入

    一.目标:编写SQL动态查询 SQL常常和程序代码一起使用.我们通常所说的SQL动态查询,是指将程序中的变量和基本SQL语句拼接成一个完整的查询语句. string sql = SELECT * FR ...

  7. 开发反模式(GUID) - 伪键洁癖

    一.目标:整理数据 有的人有强迫症,他们会为一系列数据的断档而抓狂. 一方面,Id为3这一行确实发生过一些事情,为什么这个查询不返回Id为3的这一行?这条记录数据丢失了吗?那个Column到底是什么? ...

  8. 查询反模式 - 正视NULL值

    一.提出问题 不可避免地,我们都数据库总有一些字段是没有值的.不管是插入一个不完整的行,还是有些列可以合法地拥有一些无效值.SQL 支持一个特殊的空值,就是NULL. 在很多时候,NULL值导致我们的 ...

  9. Python教程(1.2)——Python交互模式

    上一节已经说过,安装完Python,在命令行输入"python"之后,如果成功,会得到类似于下面的窗口: 可以看到,结尾有3个>符号(>>>).>&g ...

随机推荐

  1. iOS开发--隐藏(去除)导航栏底部横线

    iOS开发大部分情况下会使用到导航栏,由于我司的app导航栏需要与下面紧挨着的窗口颜色一致,导航栏底部的横线就会影响这个美观,LZ使用了以下方法.觉得不错,分享来给小伙伴们. 1)声明UIImageV ...

  2. iOS 正则表达式判断邮箱、身份证..是否正确

    //邮箱 + (BOOL) validateEmail:(NSString *)email { NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Z ...

  3. 短信SMS的接收

    近日,看了<第一行代码>有关短信接收的内容,就总结了一下. 1.手机接收到一条短信时,系统会发出一条android.provider.Telephy.SMS_RECEIVER的广播,这条广 ...

  4. CMD命令名详细大全

    在运行菜单里键入CMD,就可以调出CMD命令窗口,有关某个命令的详细信息,请键入 HELP 命令名 ASSOC 显示或修改文件扩展名关联. AT 计划在计算机上运行的命令和程序.ATTRIB 显示或更 ...

  5. Linux线程学习(二)

    线程基础 进程 系统中程序执行和资源分配的基本单位 每个进程有自己的数据段.代码段和堆栈段 在进行切换时需要有比较复杂的上下文切换   线程 减少处理机的空转时间,支持多处理器以及减少上下文切换开销, ...

  6. 关于zend_parse_parameters函数

    PHP_FUNCTION(set_time_limit) { long new_timeout; char *new_timeout_str; int new_timeout_strlen; if ( ...

  7. 百度推出的echarts,制表折线图柱状图饼图等的超级工具(转)

    一.简介: 1.绘制数据图表,有了它,想要网页上绘制个折线图.柱状图,从此easy. 2.使用这个百度的echarts.js插件,是通过把图片绘制在canvas上在显示在页面上. 官网对echarts ...

  8. 问题解决——WSAAsyncSelect模型 不触发 FD_CLOSE

    ==================================声明================================== 本文原创,转载在正文中显要的注明作者和出处,并保证文章的完 ...

  9. MySQL的诡异同步问题-重复执行一条relay-log

    MySQL的诡异同步问题 近期遇到一个诡异的MySQL同步问题,经过多方分析和定位后发现居然是由于备份引发的,非常的奇葩,特此记录一下整个问题的分析和定位过程. 现象 同事扩容的一台slave死活追不 ...

  10. Super A^B mod C

    Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,C<=1000000000,1<=B ...