python 反模式

简介: 不使用 pythonic 的循环:l = [1,2,3]#Badfor i in range(0,len(list)): le = l[i] print(i,le)#Goodfor i,le in enumerate(l): print(i,le)函数调用返回...

不使用 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]
目录
相关文章
|
5月前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
5月前
|
Python
Python中的装饰器:优雅而强大的编程利器
在Python编程中,装饰器是一种强大的工具,它可以简洁地实现代码重用、增强函数功能以及实现横切关注点的分离。本文将深入探讨Python中装饰器的原理、用法和实际应用,帮助读者更好地理解和运用这一技术。
|
4月前
|
Python
python常用代码大全分享
python常用代码大全分享
46 0
|
5月前
|
机器学习/深度学习 数据可视化 数据挖掘
实用技巧:提高 Python 编程效率的五个方法
本文介绍了五个提高 Python 编程效率的实用技巧,包括使用虚拟环境管理依赖、掌握列表推导式、使用生成器提升性能、利用装饰器简化代码结构以及使用 Jupyter Notebook 进行交互式开发。通过掌握这些技巧,可以让你的 Python 编程更加高效。
|
5月前
|
缓存 安全 中间件
《Python中的装饰器:优雅而强大的编程利器》
在Python编程领域,装饰器是一种强大而又优雅的工具,它能够有效地增强函数或者类的功能,提高代码的可读性和灵活性。本文将深入探讨Python中装饰器的原理、用法以及实际应用,帮助读者更好地理解和运用这一技术。
|
5月前
|
分布式计算 IDE 开发工具
如何提高 Python 编程效率
Python 是一种易学、易用的编程语言,但是在实际开发中,我们也会遇到各种各样的问题。本文将分享一些实用的技巧,帮助你提高 Python 编程效率。
|
10月前
|
前端开发 JavaScript PHP
Python(三十三)python模块化编程
1 :模块的定义 模块:用来从逻辑上组织Python代码(变量,函数、类,逻辑:实现一个功能),本质就是.py结尾的Python文件(文件名:test.py,对应的模块名,test)。 2 :模块的引用 模块的引用大概有三种方式: python 复制代码 import module_test, module_test1 # 调用方法的时候,需要module_test. form moudule_test import * # * 表示所有的方法(不建议使用,这个就相当于导入了程序。) 容易造成覆盖,出现问题。 form module_test import module_ajun
86 0
|
11月前
|
程序员 索引 Python
109 python高级 - 编码风格
109 python高级 - 编码风格
62 0
BXA
|
算法 数据挖掘 测试技术
Python高效编程技巧,让代码更优雅
Python是一种高级编程语言。和其他编程语言相比Python的语法更加简单、清晰,易于理解和上手。同时Python还提供了很多常用的标准库和第三方库,方便开发者快速开发出高质量的软件产品
BXA
259 0
下一篇
无影云桌面