Effective Python2 读书笔记2
Item 14: Prefer Exceptions to Returning None
Functions that returns None to indicate special meaning are error prone because None and other values (e.g., zero, the empty string) all evaluate to False in conditional expressions.
Raise exceptions to indicate special situations instead of returning None. Expect the calling code to handle exceptions properly when they're documented.
Item 15: Know How Closures Interact with Variable Scope
# found never change
def sort_priority(numbers, group):
found = False
def helper(x):
if x in group:
found = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found # use a mutable value, for example list
def sort_priority(numbers, group):
found = [False]
def helper(x):
if x in group:
found[0] = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found
Closure functions can refer to variables from any of the scopes in which they were defined.
By default, closures can't affect enclosing scopes by assigning variables.
In Python 2, use a mutable value (like a single-item list) to work around the lack of the nonlocal statement.
Avoid using nonlocal statements for anything beyond simple functions.
Item 16: Consider Generators Instead of Returning Lists
Using iterator can be clearer than the alternative of returning lists of accumulated results.
The iterator returned by a generator produces the set of values passed to yield expressions within the generator function's body.
Generators can produce a sequence of outputs for arbitrarily large inputs because their working memory doesn't include all inputs and outputs.
Item 17: Be Defensive When Iterating Over Arguments
The iterator protocol is how Python for loops and related expressions traverse the contents of a container type. When Python sees a statement like for x in foo it will actually call iter(foo). The iter built-in function calls the foo.__iter__ special method in turn. The __iter__ method must return an iterator object (which itself implements the __next__ special method). Then the for loop repeatedly calls the next built-in function on the iterator object until it's exhausted (and raises a StopIteration exception).
Practically speaking you can achieve all of this behavior for your classes by implementing the __iter__ method as a generator.
The protocol states that when an iterator is passed to the iter built-in function, iter will return the iterator itself. In contrast, when a container type is passed to iter, a new iterator object will be returned each time.
>>> class MyContainer(object):
... def __iter__(self):
... return (_ for _ in xrange(5))
...
>>> gen = MyContainer() # a new iterator object will be returned each time
>>> [_ for _ in gen]
[0, 1, 2, 3, 4]
>>> [_ for _ in gen]
[0, 1, 2, 3, 4]
>>> [_ for _ in gen]
[0, 1, 2, 3, 4] >>> iterator = (_ for _ in xrange(5)) # return the iterator itself
>>> [_ for _ in iterator]
[0, 1, 2, 3, 4]
>>> [_ for _ in iterator]
[]
>>> [_ for _ in iterator]
[]
Thus, you can test an input value for this behavior and raise a TypeError to reject iterators. It will work for any type of container that follows the iterator protocol.
def normalize_defensive(numbers):
if iter(numbers) is iter(numbers): # An iterator - bad!
raise TypeError('Must supply a container')
# sum will call ReadVisits.__iter__ to allocate a new iterator object
total = sum(numbers)
result = []
# for loop will also call __iter__ to allocate a second iterator object
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
>>> lst = [1,2,3]
>>> iter(lst) == iter(lst)
False >>> gen = (_ for _ in xrange(4))
>>> iter(gen) == iter(gen)
True
Item 18: Reduce Visual Noise with Variable Positional Arguments
>>> lst
[1, 2, 3] # join!
>>> ','.join(str(x) for x in lst)
'1,2,3'
>>> ','.join([str(x) for x in lst])
'1,2,3'
>>> ','.join((str(x) for x in lst))
'1,2,3'
Functions can accept a variable number of positional arguments by using *args in the def statement.
You can use the items from a sequence as the positional arguments for a function with the * operator.
Using the * operator with a generator may cause your program to run out of memory and crash.
Adding new positional parameters to functions that accept *args can introduce hard-to-find bugs.
Item 19: Provide Optional Behavior with Keyword Arguments
Function arguments can be specified by position or by keyword.
Keywords make it clear what the purpose of each argument is when it would be confusing with only positional arguments.
Keyword arguments with default values make it easy to add new behaviors to a function, especially when the function has existing callers.
Optional keyword arguments should always be passed by keyword instead of by position.
Item 20: Use None and Docstrings to Specify Dynamic Default Arguments
Default arguments are only evaluated once: during function definition at module load time. This can cause odd behaviors for dynamic values (like {} or []).
Use None as the default value for keyword arguments that have a dynamic value. Document the actual default behavior in the function's docstring.
Item 21: Enforce Clarity with Keyword-Only Arguments
def safe_division_d(number, divisor, **kwargs):
ignore_overflow = kwargs.pop('ignore_overflow', False)
ignore_zero_div = kwargs.pop('ignore_zero_division', False)
if kwargs:
raise TypeError("Unexcepted **kwrags: %r" % kwargs)
# ... # raise Exception
safe_division_d(1, 0, False, True) >>>
TypeError: safe_division_d() takes 2 positional arguments but 4 were given # it works
safe_division_d(1, 0, ignore_zero_division=True)
Keyword arguments make the intention of a function call more clear.
Use Keyword-only arguments to force callers to supply keyword arguments for potentially confusing functions, especially those that accept mutiple Boolean flags.
Python 2 can emulate keyword-only arguments for functions by using **kwargs and manually raising TypeError exceptions.
Effective Python2 读书笔记2的更多相关文章
- Effective Python2 读书笔记1
Item 2: Follow the PEP 8 Style Guide Naming Naming functions, variables, attributes lowercase_unders ...
- Effective Python2 读书笔记3
Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples For example, say you wa ...
- Effective STL 读书笔记
Effective STL 读书笔记 标签(空格分隔): 未分类 慎重选择容器类型 标准STL序列容器: vector.string.deque和list(双向列表). 标准STL管理容器: set. ...
- Effective STL读书笔记
Effective STL 读书笔记 本篇文字用于总结在阅读<Effective STL>时的笔记心得,只记录书上描写的,但自己尚未熟练掌握的知识点,不记录通用.常识类的知识点. STL按 ...
- effective c++读书笔记(一)
很早之前就听过这本书,找工作之前读一读.看了几页,个人感觉实在是生涩难懂,非常不符合中国人的思维方式.之前也有博主做过笔记,我来补充一些自己的理解. 我看有人记了笔记,还不错:http://www.3 ...
- Effective Java读书笔记完结啦
Effective Java是一本经典的书, 很实用的Java进阶读物, 提供了各个方面的best practices. 最近终于做完了Effective Java的读书笔记, 发布出来与大家共享. ...
- Effective java读书笔记
2015年进步很小,看的书也不是很多,感觉自己都要废了,2016是沉淀的一年,在这一年中要不断学习.看书,努力提升自己 计在16年要看12本书,主要涉及java基础.Spring研究.java并发.J ...
- Effective Objective-C 读书笔记
一本不错的书,给出了52条建议来优化程序的性能,对初学者有不错的指导作用,但是对高级阶段的程序员可能帮助不是很大.这里贴出部分笔记: 第2条: 使用#improt导入头文件会把头文件的内容全部暴露到目 ...
- 【Effective C++读书笔记】序
C++ 是一个难学易用的语言! [C++为什么难学?] C++的难学,不仅在其广博的语法,以及语法背后的语义,以及语义背后的深层思维,以及深层思维背后的对象模型: C++的难学还在于它提供了四种不同而 ...
随机推荐
- 2016-2017-2 《Java程序设计》课程学生博客和代码托管链接
2016-2017-2 <Java程序设计>课程学生博客和代码托管链接 博客 1552 20155201 李卓雯 20155202 张 旭 20155203 杜可欣 20155204 王 ...
- Oracle系列——开发中奇葩问题你遇到几个(一)
前言:在使用oracle数据进行开发的时候有没有经常出现一些很奇怪.很纳闷.很无厘头的问题呢.下面是本人使用oracle一段时间遇到的问题小节,在此做个记录,方便以后再遇到类似的问题能快速解决.如果你 ...
- iOS中UI阶段常用的一些方法
UI 即 UserInterface(用户界面 1.iOS系统版本,每年都有更新.对我们开发者而言,主要的是观察API的变化. 2.iPhone新手机发布,会产生不同尺寸的屏幕,现在市面上有4种尺寸, ...
- 读取本地外网IP地址
读取本地外网IP地址. 根据启动并运行的网卡名称,找到本机实际的IP地址(已知当前运行的无线网卡名包含某一个字符) import java.net.InterfaceAddress; import j ...
- 教你一招:解决安装或卸载office时 提示错误2503 2502 发生了内部错误
问题重现: 解决办法:使用软件卸载工具 Uninstall Tool 3.5.1 中文破解版强制删除文件,非常暴力,完美解决. 解决过程一览: 工具下载地址: 软件卸载工具 Uninstall Too ...
- BZOJ4520 [Cqoi2016]K远点对
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...
- BZOJ2242 [SDOI2011]计算器
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000 作者博客:http://www.cnblogs.com/ljh2000-jump/ ...
- C#操作剪贴板
操作剪贴版,主要用到了ClipBoard类. 该类位于 System.Windows(WPF)或System.Windows.Forms(Winform)下. 1.设置内容到剪贴版上: 主要用到Cli ...
- 理解DOM
http://www.cnblogs.com/chaogex/p/3959723.html 文档对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展标志语言 ...
- grunt自动化构建工具
一.什么是grunt? 是基于nodejs的项目构建工具,grunt和grunt插件是通过npm安装并管理的,npm是node.js的包管理器 二.为什么要用grunt? 自动化.对于反复重复的任务, ...