Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 33f73a1

Browse filesBrowse files
authored
Merge pull request fluentpython#3 from eumiro/py36plus
Modernize code to Python 3.6+ and some cleanup
2 parents ace44ee + b69e0c2 commit 33f73a1
Copy full SHA for 33f73a1

File tree

Expand file treeCollapse file tree

86 files changed

+153
-189
lines changed
Open diff view settings
Filter options

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Dismiss banner
Expand file treeCollapse file tree

86 files changed

+153
-189
lines changed
Open diff view settings
Collapse file

‎01-data-model/vector2d.py‎

Copy file name to clipboardExpand all lines: 01-data-model/vector2d.py
+1-2Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
>>> abs(v * 3)
2727
15.0
2828
29-
3029
"""
3130

3231

@@ -39,7 +38,7 @@ def __init__(self, x=0, y=0):
3938
self.y = y
4039

4140
def __repr__(self):
42-
return 'Vector(%r, %r)' % (self.x, self.y)
41+
return f'Vector({self.x!r}, {self.y!r})'
4342

4443
def __abs__(self):
4544
return hypot(self.x, self.y)
Collapse file

‎02-array-seq/bisect_demo.py‎

Copy file name to clipboardExpand all lines: 02-array-seq/bisect_demo.py
+11-11Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111
23 @ 11 | | | | | | | | | | |23
1212
22 @ 9 | | | | | | | | |22
1313
10 @ 5 | | | | |10
14-
8 @ 5 | | | | |8
15-
5 @ 3 | | |5
16-
2 @ 1 |2
17-
1 @ 1 |1
18-
0 @ 0 0
14+
8 @ 5 | | | | |8
15+
5 @ 3 | | |5
16+
2 @ 1 |2
17+
1 @ 1 |1
18+
0 @ 0 0
1919
2020
2121
Demonstration of ``bisect.bisect_left``::
@@ -27,11 +27,11 @@
2727
23 @ 9 | | | | | | | | |23
2828
22 @ 9 | | | | | | | | |22
2929
10 @ 5 | | | | |10
30-
8 @ 4 | | | |8
31-
5 @ 2 | |5
32-
2 @ 1 |2
33-
1 @ 0 1
34-
0 @ 0 0
30+
8 @ 4 | | | |8
31+
5 @ 2 | |5
32+
2 @ 1 |2
33+
1 @ 0 1
34+
0 @ 0 0
3535
3636
3737
"""
@@ -59,7 +59,7 @@ def demo(bisect_fn):
5959
bisect_fn = bisect.bisect
6060

6161
print('DEMO:', bisect_fn.__name__) # <5>
62-
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
62+
print('haystack ->', ' '.join(f'{n:2}' for n in HAYSTACK))
6363
demo(bisect_fn)
6464

6565
# END BISECT_DEMO
Collapse file

‎02-array-seq/bisect_insort.py‎

Copy file name to clipboardExpand all lines: 02-array-seq/bisect_insort.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77

88
my_list = []
99
for i in range(SIZE):
10-
new_item = random.randrange(SIZE*2)
10+
new_item = random.randrange(SIZE * 2)
1111
bisect.insort(my_list, new_item)
12-
print('%2d ->' % new_item, my_list)
12+
print(f'{new_item:2} ->', my_list)
Collapse file

‎02-array-seq/listcomp_speed.py‎

Copy file name to clipboardExpand all lines: 02-array-seq/listcomp_speed.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def non_ascii(c):
1010

1111
def clock(label, cmd):
1212
res = timeit.repeat(cmd, setup=SETUP, number=TIMES)
13-
print(label, *('{:.3f}'.format(x) for x in res))
13+
print(label, *(f'{x:.3f}' for x in res))
1414

1515
clock('listcomp :', '[ord(s) for s in symbols if ord(s) > 127]')
1616
clock('listcomp + func :', '[ord(s) for s in symbols if non_ascii(ord(s))]')
Collapse file

‎02-array-seq/metro_lat_long.py‎

Copy file name to clipboardExpand all lines: 02-array-seq/metro_lat_long.py
+3-4Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
Demonstration of nested tuple unpacking::
55
66
>>> main()
7-
| lat. | long.
7+
| lat. | long.
88
Mexico City | 19.4333 | -99.1333
99
New York-Newark | 40.8086 | -74.0204
1010
Sao Paulo | -23.5478 | -46.6358
@@ -20,11 +20,10 @@
2020
]
2121

2222
def main():
23-
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
24-
fmt = '{:15} | {:9.4f} | {:9.4f}'
23+
print(f'{"":15} | {"lat.":^9} | {"long.":^9}')
2524
for name, cc, pop, (latitude, longitude) in metro_areas: # <2>
2625
if longitude <= 0: # <3>
27-
print(fmt.format(name, latitude, longitude))
26+
print(f'{name:15} | {latitude:9.4f} | {longitude:9.4f}')
2827

2928
if __name__ == '__main__':
3029
main()
Collapse file

‎03-dict-set/index_default.py‎

Copy file name to clipboardExpand all lines: 03-dict-set/index_default.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
for line_no, line in enumerate(fp, 1):
1717
for match in WORD_RE.finditer(line):
1818
word = match.group()
19-
column_no = match.start()+1
19+
column_no = match.start() + 1
2020
location = (line_no, column_no)
2121
index[word].append(location) # <2>
2222

Collapse file

‎03-dict-set/support/container_perftest.py‎

Copy file name to clipboardExpand all lines: 03-dict-set/support/container_perftest.py
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ def test(container_type, verbose):
4141
size=size, verbose=verbose)
4242
test = TEST.format(verbose=verbose)
4343
tt = timeit.repeat(stmt=test, setup=setup, repeat=5, number=1)
44-
print('|{:{}d}|{:f}'.format(size, MAX_EXPONENT + 1, min(tt)))
44+
print(f'|{size:{MAX_EXPONENT + 1}d}|{min(tt):f}')
4545

46-
if __name__=='__main__':
46+
if __name__ == '__main__':
4747
if '-v' in sys.argv:
4848
sys.argv.remove('-v')
4949
verbose = True
5050
else:
5151
verbose = False
5252
if len(sys.argv) != 2:
53-
print('Usage: %s <container_type>' % sys.argv[0])
53+
print(f'Usage: {sys.argv[0]} <container_type>')
5454
else:
5555
test(sys.argv[1], verbose)
Collapse file

‎03-dict-set/support/container_perftest_datagen.py‎

Copy file name to clipboardExpand all lines: 03-dict-set/support/container_perftest_datagen.py
+7-7Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
Generate data for container performance test
33
"""
44

5-
import random
65
import array
6+
import random
77

88
MAX_EXPONENT = 7
99
HAYSTACK_LEN = 10 ** MAX_EXPONENT
@@ -12,26 +12,26 @@
1212

1313
needles = array.array('d')
1414

15-
sample = {1/random.random() for i in range(SAMPLE_LEN)}
16-
print('initial sample: %d elements' % len(sample))
15+
sample = {1 / random.random() for i in range(SAMPLE_LEN)}
16+
print(f'initial sample: {len(sample)} elements')
1717

1818
# complete sample, in case duplicate random numbers were discarded
1919
while len(sample) < SAMPLE_LEN:
20-
sample.add(1/random.random())
20+
sample.add(1 / random.random())
2121

22-
print('complete sample: %d elements' % len(sample))
22+
print(f'complete sample: {len(sample)} elements')
2323

2424
sample = array.array('d', sample)
2525
random.shuffle(sample)
2626

2727
not_selected = sample[:NEEDLES_LEN // 2]
28-
print('not selected: %d samples' % len(not_selected))
28+
print(f'not selected: {len(not_selected)} samples')
2929
print(' writing not_selected.arr')
3030
with open('not_selected.arr', 'wb') as fp:
3131
not_selected.tofile(fp)
3232

3333
selected = sample[NEEDLES_LEN // 2:]
34-
print('selected: %d samples' % len(selected))
34+
print(f'selected: {len(selected)} samples')
3535
print(' writing selected.arr')
3636
with open('selected.arr', 'wb') as fp:
3737
selected.tofile(fp)
Collapse file

‎03-dict-set/support/hashdiff.py‎

Copy file name to clipboardExpand all lines: 03-dict-set/support/hashdiff.py
+6-6Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import sys
22

33
MAX_BITS = len(format(sys.maxsize, 'b'))
4-
print('%s-bit Python build' % (MAX_BITS + 1))
4+
print(f'{MAX_BITS + 1}-bit Python build')
55

66
def hash_diff(o1, o2):
7-
h1 = '{:>0{}b}'.format(hash(o1), MAX_BITS)
8-
h2 = '{:>0{}b}'.format(hash(o2), MAX_BITS)
7+
h1 = f'{hash(o1):>0{MAX_BITS}b}'
8+
h2 = f'{hash(o2):>0{MAX_BITS}b}'
99
diff = ''.join('!' if b1 != b2 else ' ' for b1, b2 in zip(h1, h2))
10-
count = '!= {}'.format(diff.count('!'))
10+
count = f'!= {diff.count("!")}'
1111
width = max(len(repr(o1)), len(repr(o2)), 8)
1212
sep = '-' * (width * 2 + MAX_BITS)
13-
return '{!r:{width}} {}\n{:{width}} {} {}\n{!r:{width}} {}\n{}'.format(
14-
o1, h1, ' ' * width, diff, count, o2, h2, sep, width=width)
13+
return (f'{o1!r:{width}} {h1}\n{" ":{width}} {diff} {count}\n'
14+
f'{o2!r:{width}} {h2}\n{sep}')
1515

1616
if __name__ == '__main__':
1717
print(hash_diff(1, 1.0))
Collapse file

‎03-dict-set/transformdict.py‎

Copy file name to clipboardExpand all lines: 03-dict-set/transformdict.py
+16-17Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818

1919
class TransformDict(MutableMapping):
20-
'''Dictionary that calls a transformation function when looking
20+
"""Dictionary that calls a transformation function when looking
2121
up keys, but preserves the original keys.
2222
2323
>>> d = TransformDict(str.lower)
@@ -26,18 +26,18 @@ class TransformDict(MutableMapping):
2626
True
2727
>>> set(d.keys())
2828
{'Foo'}
29-
'''
29+
"""
3030

3131
__slots__ = ('_transform', '_original', '_data')
3232

3333
def __init__(self, transform, init_dict=None, **kwargs):
34-
'''Create a new TransformDict with the given *transform* function.
34+
"""Create a new TransformDict with the given *transform* function.
3535
*init_dict* and *kwargs* are optional initializers, as in the
3636
dict constructor.
37-
'''
37+
"""
3838
if not callable(transform):
39-
msg = 'expected a callable, got %r'
40-
raise TypeError(msg % transform.__class__)
39+
raise TypeError(
40+
f'expected a callable, got {transform.__class__!r}')
4141
self._transform = transform
4242
# transformed => original
4343
self._original = {}
@@ -48,15 +48,15 @@ def __init__(self, transform, init_dict=None, **kwargs):
4848
self.update(kwargs)
4949

5050
def getitem(self, key):
51-
'D.getitem(key) -> (stored key, value)'
51+
"""D.getitem(key) -> (stored key, value)"""
5252
transformed = self._transform(key)
5353
original = self._original[transformed]
5454
value = self._data[transformed]
5555
return original, value
5656

5757
@property
5858
def transform_func(self):
59-
"This TransformDict's transformation function"
59+
"""This TransformDict's transformation function"""
6060
return self._transform
6161

6262
# Minimum set of methods required for MutableMapping
@@ -83,22 +83,22 @@ def __delitem__(self, key):
8383
# Methods overridden to mitigate the performance overhead.
8484

8585
def clear(self):
86-
'D.clear() -> None. Remove all items from D.'
86+
"""D.clear() -> None. Remove all items from D."""
8787
self._data.clear()
8888
self._original.clear()
8989

9090
def __contains__(self, key):
9191
return self._transform(key) in self._data
9292

9393
def get(self, key, default=None):
94-
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
94+
"""D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""
9595
return self._data.get(self._transform(key), default)
9696

9797
def pop(self, key, default=_sentinel):
98-
'''D.pop(k[,d]) -> v, remove key and return corresponding value.
98+
"""D.pop(k[,d]) -> v, remove key and return corresponding value.
9999
If key is not found, d is returned if given, otherwise
100100
KeyError is raised.
101-
'''
101+
"""
102102
transformed = self._transform(key)
103103
if default is _sentinel:
104104
del self._original[transformed]
@@ -108,16 +108,16 @@ def pop(self, key, default=_sentinel):
108108
return self._data.pop(transformed, default)
109109

110110
def popitem(self):
111-
'''D.popitem() -> (k, v), remove and return some (key, value) pair
111+
"""D.popitem() -> (k, v), remove and return some (key, value) pair
112112
as a 2-tuple; but raise KeyError if D is empty.
113-
'''
113+
"""
114114
transformed, value = self._data.popitem()
115115
return self._original.pop(transformed), value
116116

117117
# Other methods
118118

119119
def copy(self):
120-
'D.copy() -> a shallow copy of D'
120+
"""D.copy() -> a shallow copy of D"""
121121
other = self.__class__(self._transform)
122122
other._original = self._original.copy()
123123
other._data = self._data.copy()
@@ -137,5 +137,4 @@ def __repr__(self):
137137
except TypeError:
138138
# Some keys are unhashable, fall back on .items()
139139
equiv = list(self.items())
140-
return '%s(%r, %s)' % (self.__class__.__name__,
141-
self._transform, repr(equiv))
140+
return f'{self.__class__.__name__}({self._transform!r}, {equiv!r})'

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.