Item 2: Follow the PEP 8 Style Guide

Naming

Naming
functions, variables, attributes lowercase_underscore
protected instance attributes _leading_underscore
private instance attributes __double_leading_underscore
classes, exceptions CapitalizedWord
module-level constants ALL_CAPS

Expressions and Statements

Always use absolute names for modules when importing them, not names relative to the current module's own path.

# not good
import foo
foo.bar() # good
from foo import bar
bar()

Item 3: Know the Differences Between str and unicode

In Python2, there are two types that represent sequences of characters: str and unicode. Instances of str contain raw 8-bit values. Instances of unicode contain Unicode characters.

The most common encoding to represent Unicode characters as binary data is UTF-8. Unicode instance in Python 2 do not have an associated binary encoding. To convert Unicode characters to binary data, you must use the encode method. To convert binary data to Unicode characters, you must use the decode method.

The core of your program should use Unicode character type (unicode in Python 2) and should not assume anything about character encodings. This approach allows you to be very accepting of alternative text encoding while being strict about your output text encoding.

def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value # Instance of unicode def to_str(unicode_or_str):
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode('utf-8')
else:
value = unicode_or_str
return value # Instance of str

In Python 2, file operations default to binary encoding. But still always open file using a binary mode (like 'rb' or 'wb').

Item 4: Write Helper Functions Instead of Complex Expressions

Python's syntax makes it all too easy to write single-line expressions that are overly complicated and difficult to read.

Move complex expressions into helper functions, especially if you need to use the same logic repeatedlly.

The if/else expression provides a more readable alternative to using Boolean operators like or and and in expressions.

from urllib.parse import parse_qs
my_values = parse_qs('red=5&blue=0&green=',
keep_blank_values=True)
print(repr(my_values)) >>>
{'red': [''], 'green': [''], 'blue': ['']} # just use get method
print('Red: ', my_values.get('red'))
print('Green: ', my_values.get('green'))
print('Opacity: ', my_values.get('opacity')) >>>
Red: ['']
Green: ['']
Opacity: None # what about set a default of 0, use or operator
red = int(my_values.get('red', [''])[0] or 0)
green = int(my_values.get('green', [''])[0] or 0)
opacity = int(my_values.get('opacity', [''])[0] or 0) # use if/else expression
red = my_values.get('red')
red = int(red[0]) if red[0] else 0 # ues if/else statement
green = my_values.get('green')
if green[0]:
green = int(green[0])
else:
green = 0 # helper function, make sense
def get_first_int(values, key, default=0):
found = values.get(key, [''])
if found[0]:
found = int(found[0])
else:
found = default
return found green = get_first_int(my_values, 'green')

Item 5: Know How to Slice Sequence

lst = [1, 2, 3]
first_twenty_items = lst[:20]
last_twenty_items = lst[-20:] lst[20] >>>
IndexError: list index out of range from copy import copy, deepcopy # lst[-0:] equal to copy(lst), same as lst[:] lst = [1, 2, 3, [4, 5]]
a = copy(lst)
b = deepcopy(lst) lst[-1].append(6)
lst.append(7) print lst
print a
print b >>>
[1, 2, 3, [4, 5, 6], 7]
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5]] lst = [1, 2, 3, 4]
lst[1:] = [3]
print lst >>>
[1, 3]

Item 6: Avoid Using start, end, and stride in a Single Slice

a = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
odds = a[::2]
evens = a[1::2]
print(odds)
print(evens) >>>
['red', 'yellow', 'blue']
['orange', 'green', 'purple'] # reverse a byte string, but break for unicode
x = b'mongoose'
y = x[::-1]
print(y) >>>
b'esoognom' a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[::2] # ['a', 'c', 'e', 'g']
a[::-2] # ['h', 'f', 'd', 'b']
a[2::2] # ['c', 'e', 'g']
a[-2::-2] # ['g', 'e', 'c', 'a']
a[-2:2:-2] # ['g', 'e']
a[2:2:-2] # []

Specifying start, end, and stride in a slice can be extremely confusing. Avoid using them together in a single slice.

Item 7: Use List Comprehensions Instead of map and filter

a = [1,2,3,4,55,6,7,7,8,9]

# clear
even_squares = [x**2 for x in a if x % 2 == 0] # sucks
alt = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a)) assert even_squares == list(alt)

Item 8: Avoid More Than Two Expressions in List Comprehensions

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print flat >>>
[1, 2, 3, 4, 5, 6, 7, 8, 9] squared = [[x**2 for x in row] for row in matrix]
print squared >>>
[[1, 4, 9], [16, 25, 36], [49, 64, 81]] my_lists = [
[[1, 2, 3], [4, 5, 6]],
#...
] # not good
flat = [x for sublist1 in my_lists
for sublist2 in sublist1
for x in sublist2] # clear
flat = []
for sublist1 in my_lists:
for sublist2 in sublist1:
flat.extend(sublist2)

List comprehensions with more than two expressions are very difficult to read and should be avoided.

Item 9: Consider Generator Expressions for Large Comprehensions

Generator expressions avoid memory issues by producing outputs one at a time as an iterator.

Item 10: Prefer enumerate Over range

flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']

# usually
for i in range(len(flavor_list)):
flavor = flavor_list[i]
print('%d: %s' % (i + 1, flavor)) # enumerate
for i, flavor in enumerate(flavor_list):
print('%d: %s' % (i + 1, flavor)) # specify which enumerate should begin count
for i, flavor in enumerate(flavor_list, 1):
print('%d: %s' % (i, flavor))

Item 11: Use zip to Process Iterators in Parallel

names = ['Cecilia', 'Lise', 'Marie']
letters = [len(n) for n in names] # usually
longest_name = None
max_letters = 0 for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count print(longest_name) # using enumerate
for i, name in enumerate(names):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count # using zip
for name, count in zip(names, letters):
if count > max_letters:
longest_name = name
max_letters = count

In Python 2, use izip from the itertools built-in module when zip very large iterators.

If the lengths tht lists you want to zip aren't equal, use izip_longest.

Item 12: Avoid else Blocks After for and while Loops

Just Avoid use it.

Item 13: Take Advantage of Each Block in try/except/else/finally

Else Blocks

When the try block doesn't raise an exception, the else block will run. The else block helps you minimize the amount of code in the try block and improves readability.

def load_json_key(data, key):
try:
result_dict = json.loads(data) # May raise ValueError
except ValueError as e:
raise KeyError from e:
else:
return result_dict[key] # May raise KeyError

The else clause ensure that what follows the try/except is visually distinguished from the except block. This makes the exception propagation behavior clear.

The try/finally compound statement lets you run cleanup code regardless of whether exceptions were raised in the try block.

The else block helps you minimize the amount of code in try blocks and visually distinguish the success case from the try/except blocks.

An else block can be used to perform additional actions after a successful try block but before common cleanup in a finally block.

Effective Python2 读书笔记1的更多相关文章

  1. Effective Python2 读书笔记3

    Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples For example, say you wa ...

  2. Effective Python2 读书笔记2

    Item 14: Prefer Exceptions to Returning None Functions that returns None to indicate special meaning ...

  3. Effective STL 读书笔记

    Effective STL 读书笔记 标签(空格分隔): 未分类 慎重选择容器类型 标准STL序列容器: vector.string.deque和list(双向列表). 标准STL管理容器: set. ...

  4. Effective STL读书笔记

    Effective STL 读书笔记 本篇文字用于总结在阅读<Effective STL>时的笔记心得,只记录书上描写的,但自己尚未熟练掌握的知识点,不记录通用.常识类的知识点. STL按 ...

  5. effective c++读书笔记(一)

    很早之前就听过这本书,找工作之前读一读.看了几页,个人感觉实在是生涩难懂,非常不符合中国人的思维方式.之前也有博主做过笔记,我来补充一些自己的理解. 我看有人记了笔记,还不错:http://www.3 ...

  6. Effective Java读书笔记完结啦

    Effective Java是一本经典的书, 很实用的Java进阶读物, 提供了各个方面的best practices. 最近终于做完了Effective Java的读书笔记, 发布出来与大家共享. ...

  7. Effective java读书笔记

    2015年进步很小,看的书也不是很多,感觉自己都要废了,2016是沉淀的一年,在这一年中要不断学习.看书,努力提升自己 计在16年要看12本书,主要涉及java基础.Spring研究.java并发.J ...

  8. Effective Objective-C 读书笔记

    一本不错的书,给出了52条建议来优化程序的性能,对初学者有不错的指导作用,但是对高级阶段的程序员可能帮助不是很大.这里贴出部分笔记: 第2条: 使用#improt导入头文件会把头文件的内容全部暴露到目 ...

  9. 【Effective C++读书笔记】序

    C++ 是一个难学易用的语言! [C++为什么难学?] C++的难学,不仅在其广博的语法,以及语法背后的语义,以及语义背后的深层思维,以及深层思维背后的对象模型: C++的难学还在于它提供了四种不同而 ...

随机推荐

  1. Monk快速开发框架前期约定

    命名规则 后端命名(统一采用[前缀]骆驼命名) 所有类都必须以首字母大写开头 接口必须以I开头 业务逻辑或业务接口必须以Services结尾 数据仓储或仓储接口必须以Repository结尾 所有特效 ...

  2. 动态树之LCT(link-cut tree)讲解

    动态树是一类要求维护森林的连通性的题的总称,这类问题要求维护某个点到根的某些数据,支持树的切分,合并,以及对子树的某些操作.其中解决这一问题的某些简化版(不包括对子树的操作)的基础数据结构就是LCT( ...

  3. 项目中遇到的关于兄弟controller之间传值的问题解决

    层级关系如下 <ons-page ng-controller="tabbarIndexController"> <ons-tabbar position=&quo ...

  4. C语言常见类型占用字节数

    前言 最近笔试经常遇到c语言各类型变量所占字节数的问题,这里做一个总结好了. 类型 常见的有char.int.long.short.float.double及指针等. 字符类型 这里单只char,ch ...

  5. 亿级 Web 系统的容错性建设实践

    一. 重试机制 最容易也最简单被人想到的容错方式,当然就是“失败重试”,总而言之,简单粗暴!简单是指它的实现通常很简单,粗暴则是指使用不当,很可能会带来系统“雪崩”的风险,因为重试意味着对后端服务的双 ...

  6. PHP文件大小格式化函数合集

    比如碰到一个很大的文件有49957289167B,大家一看这么一长串的数字后面单位是字节B,还是不知道这个文件的大小是一个什么概念,我们把它转换成GB为单位,就是46.53GB.用下面这些函数就可以完 ...

  7. Windows10环境搭建Elasticsearch+Kibana+Marvel

    环境: Windows10企业版X64 Elasticsearch-2.4.1 Kibana-4.6.1 Marvel-2.0+ 步骤: 安装Elasticsearch:官网下载Elasticsear ...

  8. 给网页 title添加图片。

    在网页的title中添加 <link rel="shortcut icon" href="logo.png" /> 即可. 可以看下百度搜索的代码, ...

  9. 最大公共字串LCS问题(阿里巴巴)

    给定两个串,均由最小字母组成.求这两个串的最大公共字串LCS(Longest Common Substring). 使用动态规划解决. #include <iostream> #inclu ...

  10. NGUI 学习笔记

    1.NGUI中UI的深度关系(新版NGUI 3.9): 在同一个Panel中,不管同不同Altas,各个UI的顺序受Depth影响 在不同Panel中,UI的顺序受Panel的Depth影响 例如Pa ...