Skip to content

Commit 42861b6

Browse files
committed
ch07: example files
1 parent 1ad2662 commit 42861b6

File tree

6 files changed

+141
-0
lines changed

6 files changed

+141
-0
lines changed

07-1class-func/README.rst

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Sample code for Chapter 7 - "First-class functions"
2+
3+
From the book "Fluent Python, Second Edition" by Luciano Ramalho (O'Reilly, 2020)
4+
http://shop.oreilly.com/product/0636920273196.do

07-1class-func/bingocall.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
# tag::BINGO_DEMO[]
3+
4+
>>> bingo = BingoCage(range(3))
5+
>>> bingo.pick()
6+
1
7+
>>> bingo()
8+
0
9+
>>> callable(bingo)
10+
True
11+
12+
# end::BINGO_DEMO[]
13+
14+
"""
15+
16+
# tag::BINGO[]
17+
18+
import random
19+
20+
class BingoCage:
21+
22+
def __init__(self, items):
23+
self._items = list(items) # <1>
24+
random.shuffle(self._items) # <2>
25+
26+
def pick(self): # <3>
27+
try:
28+
return self._items.pop()
29+
except IndexError:
30+
raise LookupError('pick from empty BingoCage') # <4>
31+
32+
def __call__(self): # <5>
33+
return self.pick()
34+
35+
# end::BINGO[]

07-1class-func/clip.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
>>> clip('banana ', 6)
3+
'banana'
4+
>>> clip('banana ', 7)
5+
'banana'
6+
>>> clip('banana ', 5)
7+
'banana'
8+
>>> clip('banana split', 6)
9+
'banana'
10+
>>> clip('banana split', 7)
11+
'banana'
12+
>>> clip('banana split', 10)
13+
'banana'
14+
>>> clip('banana split', 11)
15+
'banana'
16+
>>> clip('banana split', 12)
17+
'banana split'
18+
"""
19+
20+
# tag::CLIP[]
21+
def clip(text, max_len=80):
22+
"""Return text clipped at the last space before or after max_len
23+
"""
24+
end = None
25+
if len(text) > max_len:
26+
space_before = text.rfind(' ', 0, max_len)
27+
if space_before >= 0:
28+
end = space_before
29+
else:
30+
space_after = text.rfind(' ', max_len)
31+
if space_after >= 0:
32+
end = space_after
33+
if end is None: # no spaces were found
34+
return text.rstrip()
35+
return text[:end].rstrip()
36+
# end::CLIP[]

07-1class-func/clip_introspection.rst

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
>>> from clip import clip
2+
>>> clip.__defaults__
3+
(80,)
4+
>>> clip.__code__ # doctest: +ELLIPSIS
5+
<code object clip at 0x...>
6+
>>> clip.__code__.co_varnames
7+
('text', 'max_len', 'end', 'space_before', 'space_after')
8+
>>> clip.__code__.co_argcount
9+
2

07-1class-func/clip_signature.rst

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
>>> from clip import clip
2+
>>> from inspect import signature
3+
>>> sig = signature(clip)
4+
>>> sig # doctest: +ELLIPSIS
5+
<inspect.Signature object at 0x...>
6+
>>> str(sig)
7+
'(text, max_len=80)'
8+
>>> for name, param in sig.parameters.items():
9+
... print(param.kind, ':', name, '=', param.default)
10+
...
11+
POSITIONAL_OR_KEYWORD : text = <class 'inspect._empty'>
12+
POSITIONAL_OR_KEYWORD : max_len = 80

07-1class-func/tagger.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
2+
3+
"""
4+
# tag::TAG_DEMO[]
5+
>>> tag('br') # <1>
6+
'<br />'
7+
>>> tag('p', 'hello') # <2>
8+
'<p>hello</p>'
9+
>>> print(tag('p', 'hello', 'world'))
10+
<p>hello</p>
11+
<p>world</p>
12+
>>> tag('p', 'hello', id=33) # <3>
13+
'<p id="33">hello</p>'
14+
>>> print(tag('p', 'hello', 'world', class_='sidebar')) # <4>
15+
<p class="sidebar">hello</p>
16+
<p class="sidebar">world</p>
17+
>>> tag(content='testing', name="img") # <5>
18+
'<img content="testing" />'
19+
>>> my_tag = {'name': 'img', 'title': 'Sunset Boulevard',
20+
... 'src': 'sunset.jpg', 'class': 'framed'}
21+
>>> tag(**my_tag) # <6>
22+
'<img class="framed" src="sunset.jpg" title="Sunset Boulevard" />'
23+
24+
# end::TAG_DEMO[]
25+
"""
26+
27+
28+
# tag::TAG_FUNC[]
29+
def tag(name, *content, class_=None, **attrs):
30+
"""Generate one or more HTML tags"""
31+
if class_ is not None:
32+
attrs['class'] = class_
33+
if attrs:
34+
attr_pairs = (f' {attr}="{value}"' for attr, value
35+
in sorted(attrs.items()))
36+
attr_str = ''.join(attr_pairs)
37+
else:
38+
attr_str = ''
39+
if content:
40+
elements = (f'<{name}{attr_str}>{c}</{name}>'
41+
for c in content)
42+
return '\n'.join(elements)
43+
else:
44+
return f'<{name}{attr_str} />'
45+
# end::TAG_FUNC[]

0 commit comments

Comments
 (0)