mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 15:00:18 +00:00
various typos [thanks G.P.]
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
"""Fibonacci iterator"""
|
"""Fibonacci iterator"""
|
||||||
|
|
||||||
class Fib:
|
class Fib:
|
||||||
"""iterator that yields numbers in the Fibanocci sequence"""
|
"""iterator that yields numbers in the Fibonacci sequence"""
|
||||||
|
|
||||||
def __init__(self, max):
|
def __init__(self, max):
|
||||||
self.max = max
|
self.max = max
|
||||||
|
|||||||
+95
-21
@@ -12,48 +12,93 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
from collections import MutableMapping
|
from collections import MutableMapping
|
||||||
from itertools import zip_longest as _zip_longest
|
|
||||||
|
|
||||||
class OrderedDict(dict, MutableMapping):
|
class OrderedDict(dict, MutableMapping):
|
||||||
|
'Dictionary that remembers insertion order'
|
||||||
|
# An inherited dict maps keys to values.
|
||||||
|
# The inherited dict provides __getitem__, __len__, __contains__, and get.
|
||||||
|
# The remaining methods are order-aware.
|
||||||
|
# Big-O running times for all methods are the same as for regular dictionaries.
|
||||||
|
|
||||||
|
# The internal self.__map dictionary maps keys to links in a doubly linked list.
|
||||||
|
# The circular doubly linked list starts and ends with a sentinel element.
|
||||||
|
# The sentinel element never gets deleted (this simplifies the algorithm).
|
||||||
|
# The prev/next links are weakref proxies (to prevent circular references).
|
||||||
|
# Individual links are kept alive by the hard reference in self.__map.
|
||||||
|
# Those hard references disappear when a key is deleted from an OrderedDict.
|
||||||
|
|
||||||
def __init__(self, *args, **kwds):
|
def __init__(self, *args, **kwds):
|
||||||
|
'''Initialize an ordered dictionary. Signature is the same as for
|
||||||
|
regular dictionaries, but keyword arguments are not recommended
|
||||||
|
because their insertion order is arbitrary.
|
||||||
|
|
||||||
|
'''
|
||||||
if len(args) > 1:
|
if len(args) > 1:
|
||||||
raise TypeError('expected at most 1 arguments')
|
raise TypeError('expected at most 1 arguments, got {0}'.format(len(args)))
|
||||||
if not hasattr(self, '_keys'):
|
try:
|
||||||
self._keys = []
|
self.__root
|
||||||
|
except AttributeError:
|
||||||
|
self.__root = root = _Link() # sentinel node for the doubly linked list
|
||||||
|
root.prev = root.next = root
|
||||||
|
self.__map = {}
|
||||||
self.update(*args, **kwds)
|
self.update(*args, **kwds)
|
||||||
|
|
||||||
def clear(self):
|
def clear(self):
|
||||||
del self._keys[:]
|
'od.clear() -> None. Remove all items from od.'
|
||||||
|
root = self.__root
|
||||||
|
root.prev = root.next = root
|
||||||
|
self.__map.clear()
|
||||||
dict.clear(self)
|
dict.clear(self)
|
||||||
|
|
||||||
def __setitem__(self, key, value):
|
def __setitem__(self, key, value):
|
||||||
|
'od.__setitem__(i, y) <==> od[i]=y'
|
||||||
|
# Setting a new item creates a new link which goes at the end of the linked
|
||||||
|
# list, and the inherited dictionary is updated with the new key/value pair.
|
||||||
if key not in self:
|
if key not in self:
|
||||||
self._keys.append(key)
|
self.__map[key] = link = _Link()
|
||||||
|
root = self.__root
|
||||||
|
last = root.prev
|
||||||
|
link.prev, link.next, link.key = last, root, key
|
||||||
|
last.next = root.prev = _proxy(link)
|
||||||
dict.__setitem__(self, key, value)
|
dict.__setitem__(self, key, value)
|
||||||
|
|
||||||
def __delitem__(self, key):
|
def __delitem__(self, key):
|
||||||
|
'od.__delitem__(y) <==> del od[y]'
|
||||||
|
# Deleting an existing item uses self.__map to find the link which is
|
||||||
|
# then removed by updating the links in the predecessor and successor nodes.
|
||||||
dict.__delitem__(self, key)
|
dict.__delitem__(self, key)
|
||||||
self._keys.remove(key)
|
link = self.__map.pop(key)
|
||||||
|
link.prev.next = link.next
|
||||||
|
link.next.prev = link.prev
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return iter(self._keys)
|
'od.__iter__() <==> iter(od)'
|
||||||
|
# Traverse the linked list in order.
|
||||||
|
root = self.__root
|
||||||
|
curr = root.next
|
||||||
|
while curr is not root:
|
||||||
|
yield curr.key
|
||||||
|
curr = curr.next
|
||||||
|
|
||||||
def __reversed__(self):
|
def __reversed__(self):
|
||||||
return reversed(self._keys)
|
'od.__reversed__() <==> reversed(od)'
|
||||||
|
# Traverse the linked list in reverse order.
|
||||||
def popitem(self):
|
root = self.__root
|
||||||
if not self:
|
curr = root.prev
|
||||||
raise KeyError('dictionary is empty')
|
while curr is not root:
|
||||||
key = self._keys.pop()
|
yield curr.key
|
||||||
value = dict.pop(self, key)
|
curr = curr.prev
|
||||||
return key, value
|
|
||||||
|
|
||||||
def __reduce__(self):
|
def __reduce__(self):
|
||||||
|
'Return state information for pickling'
|
||||||
items = [[k, self[k]] for k in self]
|
items = [[k, self[k]] for k in self]
|
||||||
|
tmp = self.__map, self.__root
|
||||||
|
del self.__map, self.__root
|
||||||
inst_dict = vars(self).copy()
|
inst_dict = vars(self).copy()
|
||||||
inst_dict.pop('_keys', None)
|
self.__map, self.__root = tmp
|
||||||
return (self.__class__, (items,), inst_dict)
|
if inst_dict:
|
||||||
|
return (self.__class__, (items,), inst_dict)
|
||||||
|
return self.__class__, (items,)
|
||||||
|
|
||||||
setdefault = MutableMapping.setdefault
|
setdefault = MutableMapping.setdefault
|
||||||
update = MutableMapping.update
|
update = MutableMapping.update
|
||||||
@@ -62,22 +107,51 @@ class OrderedDict(dict, MutableMapping):
|
|||||||
values = MutableMapping.values
|
values = MutableMapping.values
|
||||||
items = MutableMapping.items
|
items = MutableMapping.items
|
||||||
|
|
||||||
def __repr__(self):
|
def popitem(self, last=True):
|
||||||
|
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
|
||||||
|
Pairs are returned in LIFO order if last is true or FIFO order if false.
|
||||||
|
|
||||||
|
'''
|
||||||
if not self:
|
if not self:
|
||||||
return '{0}()'.format(self.__class__.__name__,)
|
raise KeyError('dictionary is empty')
|
||||||
|
key = next(reversed(self) if last else iter(self))
|
||||||
|
value = self.pop(key)
|
||||||
|
return key, value
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
'od.__repr__() <==> repr(od)'
|
||||||
|
if not self:
|
||||||
|
return '{0}()'.format(self.__class__.__name__)
|
||||||
return '{0}({1})'.format(self.__class__.__name__, repr(list(self.items())))
|
return '{0}({1})'.format(self.__class__.__name__, repr(list(self.items())))
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
|
'od.copy() -> a shallow copy of od'
|
||||||
return self.__class__(self)
|
return self.__class__(self)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def fromkeys(cls, iterable, value=None):
|
def fromkeys(cls, iterable, value=None):
|
||||||
|
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
|
||||||
|
and values equal to v (which defaults to None).
|
||||||
|
|
||||||
|
'''
|
||||||
d = cls()
|
d = cls()
|
||||||
for key in iterable:
|
for key in iterable:
|
||||||
d[key] = value
|
d[key] = value
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
|
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
|
||||||
|
while comparison to a regular mapping is order-insensitive.
|
||||||
|
|
||||||
|
'''
|
||||||
if isinstance(other, OrderedDict):
|
if isinstance(other, OrderedDict):
|
||||||
return all(p==q for p, q in _zip_longest(self.items(), other.items()))
|
return len(self)==len(other) and \
|
||||||
|
all(p==q for p, q in zip(self.items(), other.items()))
|
||||||
return dict.__eq__(self, other)
|
return dict.__eq__(self, other)
|
||||||
|
|
||||||
|
def __ne__(self, other):
|
||||||
|
'''od.__ne__(y) <==> od!=y. Comparison to another OD is order-sensitive
|
||||||
|
while comparison to a regular mapping is order-insensitive.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return not self == other
|
||||||
|
|||||||
+1
-1
@@ -217,7 +217,7 @@ def build_match_and_apply_functions(pattern, search, replace):
|
|||||||
<ol>
|
<ol>
|
||||||
<li><code>build_match_and_apply_functions()</code> is a function that builds other functions dynamically. It takes <var>pattern</var>, <var>search</var> and <var>replace</var>, then defines a <code>matches_rule()</code> function which calls <code>re.search()</code> with the <var>pattern</var> that was passed to the <code>build_match_and_apply_functions()</code> function, and the <var>word</var> that was passed to the <code>matches_rule()</code> function you’re building. Whoa.
|
<li><code>build_match_and_apply_functions()</code> is a function that builds other functions dynamically. It takes <var>pattern</var>, <var>search</var> and <var>replace</var>, then defines a <code>matches_rule()</code> function which calls <code>re.search()</code> with the <var>pattern</var> that was passed to the <code>build_match_and_apply_functions()</code> function, and the <var>word</var> that was passed to the <code>matches_rule()</code> function you’re building. Whoa.
|
||||||
<li>Building the apply function works the same way. The apply function is a function that takes one parameter, and calls <code>re.sub()</code> with the <var>search</var> and <var>replace</var> parameters that were passed to the <code>build_match_and_apply_functions()</code> function, and the <var>word</var> that was passed to the <code>apply_rule()</code> function you’re building. This technique of using the values of outside parameters within a dynamic function is called <em>closures</em>. You’re essentially defining constants within the apply function you’re building: it takes one parameter (<var>word</var>), but it then acts on that plus two other values (<var>search</var> and <var>replace</var>) which were set when you defined the apply function.
|
<li>Building the apply function works the same way. The apply function is a function that takes one parameter, and calls <code>re.sub()</code> with the <var>search</var> and <var>replace</var> parameters that were passed to the <code>build_match_and_apply_functions()</code> function, and the <var>word</var> that was passed to the <code>apply_rule()</code> function you’re building. This technique of using the values of outside parameters within a dynamic function is called <em>closures</em>. You’re essentially defining constants within the apply function you’re building: it takes one parameter (<var>word</var>), but it then acts on that plus two other values (<var>search</var> and <var>replace</var>) which were set when you defined the apply function.
|
||||||
<li>Finally, the <code>build_match_and_apply_functions()</code> function returns a list of two values: the two functions you just created. The constants you defined within those functions (<var>pattern</var> within <var>matchFunction</var>, and <var>search</var> and <var>replace</var> within <var>applyFunction</var>) stay with those functions, even after you return from <code>build_match_and_apply_functions()</code>. That’s insanely cool.
|
<li>Finally, the <code>build_match_and_apply_functions()</code> function returns a list of two values: the two functions you just created. The constants you defined within those functions (<var>pattern</var> within the <code>match_rule()</code> function, and <var>search</var> and <var>replace</var> within the <code>apply_rule()</code> function) stay with those functions, even after you return from <code>build_match_and_apply_functions()</code>. That’s insanely cool.
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<p>If this is incredibly confusing (and it should be, this is weird stuff), it may become clearer when you see how to use it.
|
<p>If this is incredibly confusing (and it should be, this is weird stuff), it may become clearer when you see how to use it.
|
||||||
|
|||||||
+3
-3
@@ -26,7 +26,7 @@ body{counter-reset:h1 6}
|
|||||||
|
|
||||||
<p class=d>[<a href=examples/fibonacci2.py>download <code>fibonacci2.py</code></a>]
|
<p class=d>[<a href=examples/fibonacci2.py>download <code>fibonacci2.py</code></a>]
|
||||||
<pre><code>class Fib:
|
<pre><code>class Fib:
|
||||||
"""iterator that yields numbers in the Fibanocci sequence"""
|
"""iterator that yields numbers in the Fibonacci sequence"""
|
||||||
|
|
||||||
def __init__(self, max):
|
def __init__(self, max):
|
||||||
self.max = max
|
self.max = max
|
||||||
@@ -79,7 +79,7 @@ class PapayaWhip: <span>①</span>
|
|||||||
|
|
||||||
<pre><code>
|
<pre><code>
|
||||||
class Fib:
|
class Fib:
|
||||||
<a> """iterator that yields numbers in the Fibanocci sequence""" <span>①</span></a>
|
<a> """iterator that yields numbers in the Fibonacci sequence""" <span>①</span></a>
|
||||||
|
|
||||||
<a> def __init__(self, max): <span>②</span></a></code></pre>
|
<a> def __init__(self, max): <span>②</span></a></code></pre>
|
||||||
<ol>
|
<ol>
|
||||||
@@ -104,7 +104,7 @@ class Fib:
|
|||||||
<a><samp class=p>>>> </samp><kbd>fib.__class__</kbd> <span>③</span></a>
|
<a><samp class=p>>>> </samp><kbd>fib.__class__</kbd> <span>③</span></a>
|
||||||
<samp><class 'fibonacci2.Fib'></samp>
|
<samp><class 'fibonacci2.Fib'></samp>
|
||||||
<a><samp class=p>>>> </samp><kbd>fib.__doc__</kbd> <span>④</span></a>
|
<a><samp class=p>>>> </samp><kbd>fib.__doc__</kbd> <span>④</span></a>
|
||||||
<samp>'iterator that yields numbers in the Fibanocci sequence'</samp></pre>
|
<samp>'iterator that yields numbers in the Fibonacci sequence'</samp></pre>
|
||||||
<ol>
|
<ol>
|
||||||
<li>You are creating an instance of the <code>Fib</code> class (defined in the <code>fibonacci2</code> module) and assigning the newly created instance to the variable <var>fib</var>. You are passing one parameter, <code>100</code>, which will end up as the <var>max</var> argument in <code>Fib</code>’s <code>__init__()</code> method.
|
<li>You are creating an instance of the <code>Fib</code> class (defined in the <code>fibonacci2</code> module) and assigning the newly created instance to the variable <var>fib</var>. You are passing one parameter, <code>100</code>, which will end up as the <var>max</var> argument in <code>Fib</code>’s <code>__init__()</code> method.
|
||||||
<li><var>fib</var> is now an instance of the <code>Fib</code> class.
|
<li><var>fib</var> is now an instance of the <code>Fib</code> class.
|
||||||
|
|||||||
@@ -323,7 +323,7 @@ ValueError: list.index(x): x not in list</samp></pre>
|
|||||||
<a><samp class=p>>>> </samp><kbd>is_it_true([])</kbd> <span>②</span></a>
|
<a><samp class=p>>>> </samp><kbd>is_it_true([])</kbd> <span>②</span></a>
|
||||||
<samp>no, it's false</samp>
|
<samp>no, it's false</samp>
|
||||||
<a><samp class=p>>>> </samp><kbd>is_it_true(['a'])</kbd> <span>③</span></a>
|
<a><samp class=p>>>> </samp><kbd>is_it_true(['a'])</kbd> <span>③</span></a>
|
||||||
<samp>yes, it's true</samp></pre>
|
<samp>yes, it's true</samp>
|
||||||
<a><samp class=p>>>> </samp><kbd>is_it_true([False])</kbd> <span>④</span></a>
|
<a><samp class=p>>>> </samp><kbd>is_it_true([False])</kbd> <span>④</span></a>
|
||||||
<samp>yes, it's true</samp></pre>
|
<samp>yes, it's true</samp></pre>
|
||||||
<ol>
|
<ol>
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ if __name__ == "__main__":
|
|||||||
<blockquote class=note>
|
<blockquote class=note>
|
||||||
<p><span>☞</span>In some languages, functions (that return a value) start with <code>function</code>, and subroutines (that do not return a value) start with <code>sub</code>. There are no subroutines in Python. Everything is a function, all functions return a value (even if it’s <code>None</code>), and all functions start with <code>def</code>.
|
<p><span>☞</span>In some languages, functions (that return a value) start with <code>function</code>, and subroutines (that do not return a value) start with <code>sub</code>. There are no subroutines in Python. Everything is a function, all functions return a value (even if it’s <code>None</code>), and all functions start with <code>def</code>.
|
||||||
</blockquote>
|
</blockquote>
|
||||||
<p>The <code>approximate_size</code> function takes the two arguments — <var>size</var> and <var>a_kilobyte_is_1024_bytes</var> — but neither argument specifies a datatype. In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally.
|
<p>The <code>approximate_size()</code> function takes the two arguments — <var>size</var> and <var>a_kilobyte_is_1024_bytes</var> — but neither argument specifies a datatype. In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally.
|
||||||
<blockquote class="note compare java">
|
<blockquote class="note compare java">
|
||||||
<p><span>☞</span>In Java and other statically-typed languages, you must specify the datatype of the function return value and each function argument. In Python, you never explicitly specify the datatype of anything. Based on what value you assign, Python keeps track of the datatype internally.
|
<p><span>☞</span>In Java and other statically-typed languages, you must specify the datatype of the function return value and each function argument. In Python, you never explicitly specify the datatype of anything. Based on what value you assign, Python keeps track of the datatype internally.
|
||||||
</blockquote>
|
</blockquote>
|
||||||
@@ -90,7 +90,7 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
<p>Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value. Futhermore, arguments can be specified in any order by using named arguments.
|
<p>Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value. Futhermore, arguments can be specified in any order by using named arguments.
|
||||||
|
|
||||||
<p>Let’s take another look at that <code>approximate_size</code> function declaration:
|
<p>Let’s take another look at that <code>approximate_size()</code> function declaration:
|
||||||
|
|
||||||
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):</code></pre>
|
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):</code></pre>
|
||||||
|
|
||||||
@@ -136,7 +136,7 @@ SyntaxError: non-keyword arg after keyword arg</samp></pre>
|
|||||||
<h2 id=readability>Writing Readable Code</h2>
|
<h2 id=readability>Writing Readable Code</h2>
|
||||||
<p>I won’t bore you with a long finger-wagging speech about the importance of documenting your code. Just know that code is written once but read many times, and the most important audience for your code is yourself, six months after writing it (i.e. after you’ve forgotten everything but need to fix something). Python makes it easy to write readable code, so take advantage of it. You’ll thank me in six months.
|
<p>I won’t bore you with a long finger-wagging speech about the importance of documenting your code. Just know that code is written once but read many times, and the most important audience for your code is yourself, six months after writing it (i.e. after you’ve forgotten everything but need to fix something). Python makes it easy to write readable code, so take advantage of it. You’ll thank me in six months.
|
||||||
<h3 id=docstrings>Documentation Strings</h3>
|
<h3 id=docstrings>Documentation Strings</h3>
|
||||||
<p>You can document a Python function by giving it a documentation string (<code>docstring</code> for short). In this program, the <code>approximate_size</code> function has a <code>docstring</code>:
|
<p>You can document a Python function by giving it a documentation string (<code>docstring</code> for short). In this program, the <code>approximate_size()</code> function has a <code>docstring</code>:
|
||||||
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):
|
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):
|
||||||
"""Convert a file size to human-readable form.
|
"""Convert a file size to human-readable form.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user