参考,搬运

  1. http://python-web-guide.readthedocs.io/zh/latest/idiom/idiom.html
  2. 待定

1. Python支持链式比较

# bad
a = 5
if a > 1 and a < 7:
pass
# good
if 1 < a < 7:
pass

2. Python交换变量

# bad
x = 10
y = 5
tmp = x
x = y
y = tmp # good
x = 10
y = 5
x, y = y, x

3. Python中替代三目运算符?:

# bad
a = 10
b = 5
if a > b:
c = a
else:
c = b
# good
c = a if a > b else b

4. 格式化字符时多使用format函数

# bad
name = "tony"
age = 100
str = "myname : " + name + " my age : " + str(age)
str1 = "myname : %s my age : %d" % (name, age)
# good
str2 = "myname : {} my age {}".format(name, age)

5. 使用列表或者字典comprehension(推导式)

# bad
mylist = range(20)
odd_list = []
for e in mylist:
if e % 2 == 1:
odd_list.append(e)
# good
odd_list = [e for e in mylist if e % 2 == 1] # bad
user_list = [{'name': 'lucy', 'email': 'lucy@g.com'}, {'name': 'lily', 'email': 'lily@g.com'}]
user_email = {}
for user in user_list:
if 'email' in user:
user_email[user['name']] = user['email']
# good
{user['name']: user['email'] for user in user_list if 'email' in user}

6. 条件判断时,避免直接和True, False, None进行比较(==)

# bad
if l == []:
pass
# good
if l: # 实际调用l.__len__() == 0
pass # bad
if something == None:
# good, None 是单例对象
if something is None:

7. 使用enumerate代替for循环中的index变量访问

# bad
my_container = ['lily', 'lucy', 'tom']
index = 0
for element in my_container:
print '{} {}'.format(index, element)
index += 1 # good
for index, element in enumerate(my_container):
print '%d %s' % (index, element)

8. 避免使用可变(mutable)变量作为函数参数的默认初始化值

# bad
def function(l = []):
l.append(1)
return l print function()
print function()
print function() # print
[1]
[1, 1]
[1, 1, 1] # good 使用None作为可变对象占位符
def function(l=None):
if l is None:
l = []
l.append(1)
return l

9. 一切皆对象

# bad
def print_addition_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x + y) + '\n') def print_subtraction_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x - y) + '\n') def print_multiplication_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x * y) + '\n') def print_division_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x / y) + '\n') print_addition_table()
print_subtraction_table()
print_multiplication_table()
print_division_table() # good, python一切都是对象,可以函数作为参数,类似技巧可以用来简化代码
import operator as op def print_table(operator):
for x in range(1, 3):
for y in range(1, 3):
print(str(operator(x, y)) + '\n') for operator in (op.add, op.sub, op.mul, op.div):
print_table(operator)

10. 防御式编程EAFP vs LBYL

# LBYL
def getPersonInfo(person):
if person == None:
print 'person must be not null!'
print person.info # EAFP
def getPersonInfo(person):
try:
print person.info
except NameError:
print 'person must be not null!'

11. 用dict对象完成switch...case...的功能

# bad
def apply_operation(left_operand, right_operand, operator):
if operator == '+':
return left_operand + right_operand
elif operator == '-':
return left_operand - right_operand
elif operator == '*':
return left_operand * right_operand
elif operator == '/':
return left_operand / right_operand
# good
def apply_operation(left_operand, right_operand, operator):
import operator as op
operator_mapper = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv}
return operator_mapper[operator](left_operand, right_operand)

12. 访问tuple的数据项时,可以用namedtuple代替index的方式访问

# bad
rows = [('lily', 20, 2000), ('lucy', 19, 2500)]
for row in rows:
print '{}`age is {}, salary is {} '.format(row[0], row[1], row[2]) # good
from collections import namedtuple
Employee = namedtuple('Employee', 'name, age, salary')
for row in rows:
employee = Employee._make(row)
print '{}`age is {}, salary is {} '.format(employee.name, employee.age, employee.salary)

13. 用isinstance来判断对象的类型

下面的代码是计算一个对象的长度值,如果是序列类型(str,list,set,dict)的, 直接调用len方法,如果是True, False, None则返回1,如果是数值的,则返回其int值.

# bad
def get_size(some_object):
try:
return len(some_object)
except TypeError:
if some_object in (True, False, None):
return 1
else:
return int(some_object) print(get_size('hello'))
print(get_size([1, 2, 3, 4, 5]))
print(get_size(10.0)) # good
def get_size(some_object):
if isinstance(some_object, (list, dict, str, tuple)):
return len(some_object)
elif isinstance(some_object, (bool, type(None))):
return 1
elif isinstance(some_object, (int, float)):
return int(some_object)

14. 用with管理操作资源的上下文环境

上下文协议需要实现__enter__和__exit__方法

# bad
class Connection(object):
def execute(self, sql):
raise Exception('ohoh, exception!') def close(self):
print 'closed the Connection' try:
conn = Connection()
conn.execute('select * from t_users')
finally:
conn.close() # good
class Connection(object):
def execute(self, sql):
raise Exception('ohoh, exception!') def close(self):
print 'closed the Connection' def __enter__(self):
return self def __exit__(self, errorType, errorValue, error):
self.close() with Connection() as conn:
conn.execute('select * from t_users')

15. 使用generator返回耗费内存的对象

# bad
def f():
# ...
return biglist # bad
def f():
# ...
return biglist # good
def f():
# ...
for i in biglist:
yield i

Python - 编程技巧,语法糖,黑魔法,pythonic的更多相关文章

  1. python编程技巧2

    模块化 ---- 这是我们程序员梦寐以求的,通过模块化可以避免重复的制造轮子. 同时 模块让你能够有逻辑地组织你的Python代码段. 把相关的代码分配到一个 模块里能让你的代码更好用,更易懂. 模块 ...

  2. python的一些语法糖

    1   Python中if-else语句的多种写法 a, b, c = 1, 2, 3 1.常规 if a>b: c = a else: c = b 2.表达式 c = a if a>b  ...

  3. 一十九条优雅Python编程技巧

    1.交换赋值 #不推荐 temp = a a = b b = a #推荐 a , b = b , a #先生成一个元组(tuple)对象,然后在unpack 2.Unpacking #不推荐 l = ...

  4. Python 编程技巧

    Python 生成器 Python 处理文件 Python 异常处理 Python 处理输入输出 Python 处理命令行参数 Python 对文件做校验 Python 对目录做遍历 Python 调 ...

  5. python装饰器 语法糖

    简介: 装饰器(Decorators)是 Python 的一个重要部分.简单地说:他们是修改其他函数的功能的函数. 比如说我们写flask,路由就是用装饰器定义的.如果写权限控制,那么权限控制一般也是 ...

  6. python 装饰器(语法糖)

    def  login(func):    def testlogin():        for  i in range(3):            _username="abc" ...

  7. python编程技巧

  8. 【Python】从1<2<3的语法糖说起

    python有一个很有意思的语法糖你可以直接写1<2<3. 这复合我们通常意义上的数学不等式,但对学过C等语言其实是有疑惑的. 我们知道不等式返回的其实是个Bool值,在C中是1,0因此C ...

  9. 学习 Python 编程的 19 个资源 (转)

    学习 Python 编程的 19 个资源 2018-01-07 数据与算法之美 编译:wzhvictor,英文:codecondo segmentfault.com/a/119000000418731 ...

随机推荐

  1. Bug搬运工-Forerunner CRC error on 54SG/53SG3 triggers watchdog timeout crash

    这个bug,一般是设备4948 Crash的情况: 标志1:Error Message C4K_SUPERVISOR-2-SOFTERROR: memory inconsistency detecte ...

  2. 每天进步一点点------SOPC TIMER (一)

    寄存器图 可以通过操作以下的寄存器来实现对timer(定时器)内核的操作(仅描述32位计数器) 状态寄存器: TO(timeout) :计数器计数到0时,该位置1,之后TO位的值会保持,直到手动清零, ...

  3. pip install 安装指定版本的包

    pip install 安装指定版本的包   要用 pip 安装指定版本的 Python 包,只需通过 == 操作符 指定 pip install robotframework==2.8.7 将安装r ...

  4. web学习---html,js,php,mysql一个动态网页获取流程

    使用bootstrap的cms模版系统搭建了一个信息管理系统.通过这个系统学习动态网页获取的工作流程. 抓包分析一个页面的数据请求流程如下图所示: 同样,对于需要向数据库插入数据,可以使用ajax接口 ...

  5. Fiddler修改http请求响应简单实例

    Fiddler是一个http调试代理,它能够记录并检查所有你的电脑和互联网之间的http通讯. 主要功能 设置断点,查看Fiddle说有的进出的数据(指cookie,html,js,css等文件,这些 ...

  6. zabbix监控服务部署脚本

    搭建平台脚本: #!/bin/bash #zabbix监控服务部署 #脚本使用前提:yum搭建,nginx-1.12.2源码包,zabbix-3.4.4源码包,要求源码包尽量在单一目录下,最好在默认管 ...

  7. Abaqus 子模型法 和 子结构法

    目录 1 子模型法 1.2 子模型法应用考虑因素 1.3 子模型法关键技术 1.3.1 单元选择 1.3.2 驱动变量 1.3.3 链接整体模型和子模型 1.4 仿真过程 1.4.1 问题描述 1.4 ...

  8. LVS的概念和重要性

    LVS: 概念:是Linux Virtual Server的简写,意即Linux虚拟服务器,是一个虚拟的服务器集群系统 作用:举例 像有三个小区,但是工作的时间和休息的时间不一样,第一个是白天工作,一 ...

  9. ASP.NET Core搭建多层网站架构【11-WebApi统一处理返回值、异常】

    2020/02/01, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[11-WebApi统一处理返回值.异常] 使用I ...

  10. MockMVC - 基于RESTful风格的Springboot,SpringMVC的测试

    MockMVC - 基于RESTful风格的SpringMVC的测试 对于前后端分离的项目而言,无法直接从前端静态代码中测试接口的正确性,因此可以通过MockMVC来模拟HTTP请求.基于RESTfu ...