Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions 01-data-model/vector2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
>>> abs(v * 3)
15.0


"""


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

def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
return f'Vector({self.x!r}, {self.y!r})'

def __abs__(self):
return hypot(self.x, self.y)
Expand Down
22 changes: 11 additions & 11 deletions 02-array-seq/bisect_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
23 @ 11 | | | | | | | | | | |23
22 @ 9 | | | | | | | | |22
10 @ 5 | | | | |10
8 @ 5 | | | | |8
5 @ 3 | | |5
2 @ 1 |2
1 @ 1 |1
0 @ 0 0
8 @ 5 | | | | |8
5 @ 3 | | |5
2 @ 1 |2
1 @ 1 |1
0 @ 0 0


Demonstration of ``bisect.bisect_left``::
Expand All @@ -27,11 +27,11 @@
23 @ 9 | | | | | | | | |23
22 @ 9 | | | | | | | | |22
10 @ 5 | | | | |10
8 @ 4 | | | |8
5 @ 2 | |5
2 @ 1 |2
1 @ 0 1
0 @ 0 0
8 @ 4 | | | |8
5 @ 2 | |5
2 @ 1 |2
1 @ 0 1
0 @ 0 0


"""
Expand Down Expand Up @@ -59,7 +59,7 @@ def demo(bisect_fn):
bisect_fn = bisect.bisect

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

# END BISECT_DEMO
4 changes: 2 additions & 2 deletions 02-array-seq/bisect_insort.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@

my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
new_item = random.randrange(SIZE * 2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
print(f'{new_item:2} ->', my_list)
2 changes: 1 addition & 1 deletion 02-array-seq/listcomp_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def non_ascii(c):

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

clock('listcomp :', '[ord(s) for s in symbols if ord(s) > 127]')
clock('listcomp + func :', '[ord(s) for s in symbols if non_ascii(ord(s))]')
Expand Down
7 changes: 3 additions & 4 deletions 02-array-seq/metro_lat_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Demonstration of nested tuple unpacking::
>>> main()
| lat. | long.
| lat. | long.
Mexico City | 19.4333 | -99.1333
New York-Newark | 40.8086 | -74.0204
Sao Paulo | -23.5478 | -46.6358
Expand All @@ -20,11 +20,10 @@
]

def main():
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
print(f'{"":15} | {"lat.":^9} | {"long.":^9}')
for name, cc, pop, (latitude, longitude) in metro_areas: # <2>
if longitude <= 0: # <3>
print(fmt.format(name, latitude, longitude))
print(f'{name:15} | {latitude:9.4f} | {longitude:9.4f}')

if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion 03-dict-set/index_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
for line_no, line in enumerate(fp, 1):
for match in WORD_RE.finditer(line):
word = match.group()
column_no = match.start()+1
column_no = match.start() + 1
location = (line_no, column_no)
index[word].append(location) # <2>

Expand Down
6 changes: 3 additions & 3 deletions 03-dict-set/support/container_perftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ def test(container_type, verbose):
size=size, verbose=verbose)
test = TEST.format(verbose=verbose)
tt = timeit.repeat(stmt=test, setup=setup, repeat=5, number=1)
print('|{:{}d}|{:f}'.format(size, MAX_EXPONENT + 1, min(tt)))
print(f'|{size:{MAX_EXPONENT + 1}d}|{min(tt):f}')

if __name__=='__main__':
if __name__ == '__main__':
if '-v' in sys.argv:
sys.argv.remove('-v')
verbose = True
else:
verbose = False
if len(sys.argv) != 2:
print('Usage: %s <container_type>' % sys.argv[0])
print(f'Usage: {sys.argv[0]} <container_type>')
else:
test(sys.argv[1], verbose)
14 changes: 7 additions & 7 deletions 03-dict-set/support/container_perftest_datagen.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
Generate data for container performance test
"""

import random
import array
import random

MAX_EXPONENT = 7
HAYSTACK_LEN = 10 ** MAX_EXPONENT
Expand All @@ -12,26 +12,26 @@

needles = array.array('d')

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

# complete sample, in case duplicate random numbers were discarded
while len(sample) < SAMPLE_LEN:
sample.add(1/random.random())
sample.add(1 / random.random())

print('complete sample: %d elements' % len(sample))
print(f'complete sample: {len(sample)} elements')

sample = array.array('d', sample)
random.shuffle(sample)

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

selected = sample[NEEDLES_LEN // 2:]
print('selected: %d samples' % len(selected))
print(f'selected: {len(selected)} samples')
print(' writing selected.arr')
with open('selected.arr', 'wb') as fp:
selected.tofile(fp)
12 changes: 6 additions & 6 deletions 03-dict-set/support/hashdiff.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import sys

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

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

if __name__ == '__main__':
print(hash_diff(1, 1.0))
Expand Down
33 changes: 16 additions & 17 deletions 03-dict-set/transformdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


class TransformDict(MutableMapping):
'''Dictionary that calls a transformation function when looking
"""Dictionary that calls a transformation function when looking
up keys, but preserves the original keys.

>>> d = TransformDict(str.lower)
Expand All @@ -26,18 +26,18 @@ class TransformDict(MutableMapping):
True
>>> set(d.keys())
{'Foo'}
'''
"""

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

def __init__(self, transform, init_dict=None, **kwargs):
'''Create a new TransformDict with the given *transform* function.
"""Create a new TransformDict with the given *transform* function.
*init_dict* and *kwargs* are optional initializers, as in the
dict constructor.
'''
"""
if not callable(transform):
msg = 'expected a callable, got %r'
raise TypeError(msg % transform.__class__)
raise TypeError(
f'expected a callable, got {transform.__class__!r}')
self._transform = transform
# transformed => original
self._original = {}
Expand All @@ -48,15 +48,15 @@ def __init__(self, transform, init_dict=None, **kwargs):
self.update(kwargs)

def getitem(self, key):
'D.getitem(key) -> (stored key, value)'
"""D.getitem(key) -> (stored key, value)"""
transformed = self._transform(key)
original = self._original[transformed]
value = self._data[transformed]
return original, value

@property
def transform_func(self):
"This TransformDict's transformation function"
"""This TransformDict's transformation function"""
return self._transform

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

def clear(self):
'D.clear() -> None. Remove all items from D.'
"""D.clear() -> None. Remove all items from D."""
self._data.clear()
self._original.clear()

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

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

def pop(self, key, default=_sentinel):
'''D.pop(k[,d]) -> v, remove key and return corresponding value.
"""D.pop(k[,d]) -> v, remove key and return corresponding value.
If key is not found, d is returned if given, otherwise
KeyError is raised.
'''
"""
transformed = self._transform(key)
if default is _sentinel:
del self._original[transformed]
Expand All @@ -108,16 +108,16 @@ def pop(self, key, default=_sentinel):
return self._data.pop(transformed, default)

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

# Other methods

def copy(self):
'D.copy() -> a shallow copy of D'
"""D.copy() -> a shallow copy of D"""
other = self.__class__(self._transform)
other._original = self._original.copy()
other._data = self._data.copy()
Expand All @@ -137,5 +137,4 @@ def __repr__(self):
except TypeError:
# Some keys are unhashable, fall back on .items()
equiv = list(self.items())
return '%s(%r, %s)' % (self.__class__.__name__,
self._transform, repr(equiv))
return f'{self.__class__.__name__}({self._transform!r}, {equiv!r})'
2 changes: 1 addition & 1 deletion 04-text-byte/charfinder/cf.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
def find(*query_words, first=FIRST, last=LAST): # <2>
query = {w.upper() for w in query_words} # <3>
count = 0
for code in range(first, last + 1):
for code in range(first, last + 1):
char = chr(code) # <4>
name = unicodedata.name(char, None) # <5>
if name and query.issubset(name.split()): # <6>
Expand Down
2 changes: 1 addition & 1 deletion 04-text-byte/default_encodings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@

for expression in expressions.split():
value = eval(expression)
print(expression.rjust(30), '->', repr(value))
print(f'{expression:>30} -> {value!r}')
4 changes: 2 additions & 2 deletions 04-text-byte/numerics_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
sample = '1\xbc\xb2\u0969\u136b\u216b\u2466\u2480\u3285'

for char in sample:
print('U+%04x' % ord(char), # <1>
print(f'U+{ord(char):04x}', # <1>
char.center(6), # <2>
're_dig' if re_digit.match(char) else '-', # <3>
'isdig' if char.isdigit() else '-', # <4>
'isnum' if char.isnumeric() else '-', # <5>
format(unicodedata.numeric(char), '5.2f'), # <6>
f'{unicodedata.numeric(char):5.2f}', # <6>
unicodedata.name(char), # <7>
sep='\t')
# end::NUMERICS_DEMO[]
2 changes: 1 addition & 1 deletion 04-text-byte/ramanujan.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

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

print('Text', repr(text_str), sep='\n ')
print(f'Text\n {text_str!r}')
print('Numbers')
print(' str :', re_numbers_str.findall(text_str)) # <6>
print(' bytes:', re_numbers_bytes.findall(text_bytes)) # <7>
Expand Down
1 change: 0 additions & 1 deletion 04-text-byte/sanitize.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

"""
Radical folding and text sanitizing.

Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/dataclass/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Coordinate:

lat: float
long: float

def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.long >= 0 else 'W'
Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/dataclass/hackerclub.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

# tag::HACKERCLUB[]
from dataclasses import dataclass
from club import ClubMember
from club import ClubMember

@dataclass
class HackerClubMember(ClubMember): # <1>
Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/dataclass/hackerclub_annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
# tag::HACKERCLUB[]
from dataclasses import dataclass
from typing import ClassVar, Set
from club import ClubMember
from club import ClubMember

@dataclass
class HackerClubMember(ClubMember):
Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/dataclass/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
>>> description = 'Improving the design of existing code'
>>> book = Resource('978-0-13-475759-9', 'Refactoring, 2nd Edition',
... ['Martin Fowler', 'Kent Beck'], date(2018, 11, 19),
... ResourceType.BOOK, description, 'EN',
... ResourceType.BOOK, description, 'EN',
... ['computer programming', 'OOP'])
>>> book # doctest: +NORMALIZE_WHITESPACE
Resource(identifier='978-0-13-475759-9', title='Refactoring, 2nd Edition',
Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/dataclass/resource_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
>>> description = 'Improving the design of existing code'
>>> book = Resource('978-0-13-475759-9', 'Refactoring, 2nd Edition',
... ['Martin Fowler', 'Kent Beck'], date(2018, 11, 19),
... ResourceType.BOOK, description, 'EN',
... ResourceType.BOOK, description, 'EN',
... ['computer programming', 'OOP'])

# tag::DOCTEST[]
Expand Down
2 changes: 1 addition & 1 deletion 05-record-like/typing_namedtuple/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Coordinate(NamedTuple):

lat: float
long: float

def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.long >= 0 else 'W'
Expand Down
Loading