Skip to content

Commit b69e0c2

Browse files
committed
Modernize code to Python 3.6+ and some cleanup
1 parent 93bb440 commit b69e0c2

File tree

86 files changed

+153
-189
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+153
-189
lines changed

01-data-model/vector2d.py

+1-2
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)

02-array-seq/bisect_demo.py

+11-11
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

02-array-seq/bisect_insort.py

+2-2
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)

02-array-seq/listcomp_speed.py

+1-1
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))]')

02-array-seq/metro_lat_long.py

+3-4
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()

03-dict-set/index_default.py

+1-1
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

03-dict-set/support/container_perftest.py

+3-3
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)

03-dict-set/support/container_perftest_datagen.py

+7-7
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)

03-dict-set/support/hashdiff.py

+6-6
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))

03-dict-set/transformdict.py

+16-17
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})'

04-text-byte/charfinder/cf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
def find(*query_words, first=FIRST, last=LAST): # <2>
99
query = {w.upper() for w in query_words} # <3>
1010
count = 0
11-
for code in range(first, last + 1):
11+
for code in range(first, last + 1):
1212
char = chr(code) # <4>
1313
name = unicodedata.name(char, None) # <5>
1414
if name and query.issubset(name.split()): # <6>

04-text-byte/default_encodings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,4 @@
1818

1919
for expression in expressions.split():
2020
value = eval(expression)
21-
print(expression.rjust(30), '->', repr(value))
21+
print(f'{expression:>30} -> {value!r}')

04-text-byte/numerics_demo.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
sample = '1\xbc\xb2\u0969\u136b\u216b\u2466\u2480\u3285'
88

99
for char in sample:
10-
print('U+%04x' % ord(char), # <1>
10+
print(f'U+{ord(char):04x}', # <1>
1111
char.center(6), # <2>
1212
're_dig' if re_digit.match(char) else '-', # <3>
1313
'isdig' if char.isdigit() else '-', # <4>
1414
'isnum' if char.isnumeric() else '-', # <5>
15-
format(unicodedata.numeric(char), '5.2f'), # <6>
15+
f'{unicodedata.numeric(char):5.2f}', # <6>
1616
unicodedata.name(char), # <7>
1717
sep='\t')
1818
# end::NUMERICS_DEMO[]

04-text-byte/ramanujan.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
text_bytes = text_str.encode('utf_8') # <5>
1313

14-
print('Text', repr(text_str), sep='\n ')
14+
print(f'Text\n {text_str!r}')
1515
print('Numbers')
1616
print(' str :', re_numbers_str.findall(text_str)) # <6>
1717
print(' bytes:', re_numbers_bytes.findall(text_bytes)) # <7>

04-text-byte/sanitize.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
"""
32
Radical folding and text sanitizing.
43

05-record-like/dataclass/coordinates.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class Coordinate:
1616

1717
lat: float
1818
long: float
19-
19+
2020
def __str__(self):
2121
ns = 'N' if self.lat >= 0 else 'S'
2222
we = 'E' if self.long >= 0 else 'W'

05-record-like/dataclass/hackerclub.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131
# tag::HACKERCLUB[]
3232
from dataclasses import dataclass
33-
from club import ClubMember
33+
from club import ClubMember
3434

3535
@dataclass
3636
class HackerClubMember(ClubMember): # <1>

05-record-like/dataclass/hackerclub_annotated.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
# tag::HACKERCLUB[]
3232
from dataclasses import dataclass
3333
from typing import ClassVar, Set
34-
from club import ClubMember
34+
from club import ClubMember
3535

3636
@dataclass
3737
class HackerClubMember(ClubMember):

05-record-like/dataclass/resource.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
>>> description = 'Improving the design of existing code'
1515
>>> book = Resource('978-0-13-475759-9', 'Refactoring, 2nd Edition',
1616
... ['Martin Fowler', 'Kent Beck'], date(2018, 11, 19),
17-
... ResourceType.BOOK, description, 'EN',
17+
... ResourceType.BOOK, description, 'EN',
1818
... ['computer programming', 'OOP'])
1919
>>> book # doctest: +NORMALIZE_WHITESPACE
2020
Resource(identifier='978-0-13-475759-9', title='Refactoring, 2nd Edition',

05-record-like/dataclass/resource_repr.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
>>> description = 'Improving the design of existing code'
2222
>>> book = Resource('978-0-13-475759-9', 'Refactoring, 2nd Edition',
2323
... ['Martin Fowler', 'Kent Beck'], date(2018, 11, 19),
24-
... ResourceType.BOOK, description, 'EN',
24+
... ResourceType.BOOK, description, 'EN',
2525
... ['computer programming', 'OOP'])
2626
2727
# tag::DOCTEST[]

05-record-like/typing_namedtuple/coordinates.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class Coordinate(NamedTuple):
1414

1515
lat: float
1616
long: float
17-
17+
1818
def __str__(self):
1919
ns = 'N' if self.lat >= 0 else 'S'
2020
we = 'E' if self.long >= 0 else 'W'

0 commit comments

Comments
 (0)