Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize code #3072

Closed
wants to merge 3 commits into from
Closed
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
8 changes: 4 additions & 4 deletions examples/dynamic_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,11 @@ def run_steps(name, step_times, app_steps_task_id):

for idx, (name, step_times) in enumerate(apps):
# update message on overall progress bar
top_descr = "[bold #AAAAAA](%d out of %d apps installed)" % (idx, len(apps))
top_descr = f"[bold #AAAAAA]({idx} out of {len(apps)} apps installed)"
overall_progress.update(overall_task_id, description=top_descr)

# add progress bar for steps of this app, and run the steps
current_task_id = current_app_progress.add_task("Installing app %s" % name)
current_task_id = current_app_progress.add_task(f"Installing app {name}")
app_steps_task_id = app_steps_progress.add_task(
"", total=len(step_times), name=name
)
Expand All @@ -106,13 +106,13 @@ def run_steps(name, step_times, app_steps_task_id):
app_steps_progress.update(app_steps_task_id, visible=False)
current_app_progress.stop_task(current_task_id)
current_app_progress.update(
current_task_id, description="[bold green]App %s installed!" % name
current_task_id, description=f"[bold green]App {name} installed!"
)

# increase overall progress now this task is done
overall_progress.update(overall_task_id, advance=1)

# final update for message on overall progress bar
overall_progress.update(
overall_task_id, description="[bold green]%s apps installed, done!" % len(apps)
overall_task_id, description=f"[bold green]{len(apps)} apps installed, done!"
)
2 changes: 1 addition & 1 deletion examples/print_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def print_calendar(year):

for week_day in cal.iterweekdays():
table.add_column(
"{:.3}".format(calendar.day_name[week_day]), justify="right"
f"{calendar.day_name[week_day]:.3}", justify="right"
)

month_days = cal.monthdayscalendar(year, month)
Expand Down
6 changes: 2 additions & 4 deletions rich/_ratio.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,8 @@ def ratio_distribute(
distributed_total: List[int] = []
append = distributed_total.append
if minimums is None:
_minimums = [0] * len(ratios)
else:
_minimums = minimums
for ratio, minimum in zip(ratios, _minimums):
minimums = [0] * len(ratios)
for ratio, minimum in zip(ratios, minimums):
if total_ratio > 0:
distributed = max(minimum, ceil(ratio * total_remaining / total_ratio))
else:
Expand Down
5 changes: 1 addition & 4 deletions rich/_wrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@


def words(text: str) -> Iterable[Tuple[int, int, str]]:
position = 0
word_match = re_word.match(text, position)
while word_match is not None:
for word_match in re_word.finditer(text):
start, end = word_match.span()
word = word_match.group(0)
yield start, end, word
word_match = re_word.match(text, end)


def divide_line(text: str, width: int, fold: bool = True) -> List[int]:
Expand Down
5 changes: 2 additions & 3 deletions rich/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,8 @@ def generate_segments() -> Iterable[Segment]:
)

def blank_lines(count: int) -> Iterable[Segment]:
if count > 0:
for _ in range(count):
yield blank_line
for _ in range(count):
yield blank_line

vertical_height = self.height or options.height
iter_segments: Iterable[Segment]
Expand Down
6 changes: 2 additions & 4 deletions rich/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,10 @@ def __rich_console__(
return

prefix_complete_eights = int(width * 8 * self.begin / self.size)
prefix_bar_count = prefix_complete_eights // 8
prefix_eights_count = prefix_complete_eights % 8
prefix_bar_count, prefix_eights_count = divmod(prefix_complete_eights, 8)

body_complete_eights = int(width * 8 * self.end / self.size)
body_bar_count = body_complete_eights // 8
body_eights_count = body_complete_eights % 8
body_bar_count, body_eights_count = divmod(body_complete_eights, 8)

# When start and end fall into the same cell, we ideally should render
# a symbol that's "center-aligned", but there is no good symbol in Unicode.
Expand Down
7 changes: 2 additions & 5 deletions rich/cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,15 @@ def _get_codepoint_cell_size(codepoint: int) -> int:
_table = CELL_WIDTHS
lower_bound = 0
upper_bound = len(_table) - 1
index = (lower_bound + upper_bound) // 2
while True:
while lower_bound <= upper_bound:
index = (lower_bound + upper_bound) // 2
start, end, width = _table[index]
if codepoint < start:
upper_bound = index - 1
elif codepoint > end:
lower_bound = index + 1
else:
return 0 if width == -1 else width
if upper_bound < lower_bound:
break
index = (lower_bound + upper_bound) // 2
return 1


Expand Down
2 changes: 1 addition & 1 deletion rich/color_triplet.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ def normalized(self) -> Tuple[float, float, float]:
Tuple[float, float, float]: A tuple of three normalized colour components.
"""
red, green, blue = self
return red / 255.0, green / 255.0, blue / 255.0
return red / 255, green / 255, blue / 255
29 changes: 10 additions & 19 deletions rich/containers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from itertools import zip_longest
from typing import (
Iterator,
Iterable,
Expand Down Expand Up @@ -141,27 +140,19 @@ def justify(
line.truncate(width, overflow=overflow)
line.pad_left(width - cell_len(line.plain))
elif justify == "full":
for line_index, line in enumerate(self._lines):
if line_index == len(self._lines) - 1:
break
for line_index, line in enumerate(self._lines[:-1]):
words = line.split(" ")
words_size = sum(cell_len(word.plain) for word in words)
num_spaces = len(words) - 1
spaces = [1 for _ in range(num_spaces)]
index = 0
if spaces:
while words_size + num_spaces < width:
spaces[len(spaces) - index - 1] += 1
num_spaces += 1
index = (index + 1) % len(spaces)
space, longer_spaces = divmod(width - words_size, num_spaces)
spaces = [space] * (num_spaces - longer_spaces) + [space + 1] * longer_spaces

tokens: List[Text] = []
for index, (word, next_word) in enumerate(
zip_longest(words, words[1:])
):
for word, space, next_word in zip(words, spaces, words[1:]):
tokens.append(word)
if index < len(spaces):
style = word.get_style_at_offset(console, -1)
next_style = next_word.get_style_at_offset(console, 0)
space_style = style if style == next_style else line.style
tokens.append(Text(" " * spaces[index], style=space_style))
style = word.get_style_at_offset(console, -1)
next_style = next_word.get_style_at_offset(console, 0)
space_style = style if style == next_style else line.style
tokens.append(Text(" " * space, style=space_style))
tokens.append(words[-1])
self[line_index] = Text("").join(tokens)
9 changes: 2 additions & 7 deletions rich/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,13 @@ def _to_str(
if size == 1:
return "1 byte"
elif size < base:
return "{:,} bytes".format(size)
return f"{size:,} bytes"

for i, suffix in enumerate(suffixes, 2): # noqa: B007
unit = base**i
if size < unit:
break
return "{:,.{precision}f}{separator}{}".format(
(base * size / unit),
suffix,
precision=precision,
separator=separator,
)
return f"{base * size / unit:,.{precision}f}{separator}{suffix}"


def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
Expand Down
8 changes: 4 additions & 4 deletions rich/progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -1002,9 +1002,9 @@ def finished(self) -> bool:
def percentage(self) -> float:
"""float: Get progress of task as a percentage. If a None total was set, returns 0"""
if not self.total:
return 0.0
completed = (self.completed / self.total) * 100.0
completed = min(100.0, max(0.0, completed))
return 0
completed = (self.completed / self.total) * 100
completed = min(100, max(0, completed))
return completed

@property
Expand Down Expand Up @@ -1326,7 +1326,7 @@ def open(
# normalize the mode (always rb, rt)
_mode = "".join(sorted(mode, reverse=False))
if _mode not in ("br", "rt", "r"):
raise ValueError("invalid mode {!r}".format(mode))
raise ValueError(f"invalid mode {mode!r}")

# patch buffering to provide the same behaviour as the builtin `open`
line_buffering = buffering == 1
Expand Down
7 changes: 3 additions & 4 deletions rich/progress_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def _get_pulse_segments(

for index in range(PULSE_SIZE):
position = index / PULSE_SIZE
fade = 0.5 + cos((position * pi * 2)) / 2.0
fade = 0.5 + cos((position * pi * 2)) / 2
color = blend_rgb(fore_color, back_color, cross_fade=fade)
append(_Segment(bar, _Style(color=from_triplet(color))))
return segments
Expand Down Expand Up @@ -148,7 +148,7 @@ def _render_pulse(
current_time = (
monotonic() if self.animation_time is None else self.animation_time
)
segments = pulse_segments * (int(width / segment_count) + 2)
segments = pulse_segments * (width // segment_count + 2)
offset = int(-current_time * 15) % segment_count
segments = segments[offset : offset + width]
yield from segments
Expand Down Expand Up @@ -176,8 +176,7 @@ def __rich_console__(
if self.total and completed is not None
else width * 2
)
bar_count = complete_halves // 2
half_bar_count = complete_halves % 2
bar_count, half_bar_count = divmod(complete_halves, 2)
style = console.get_style(self.style)
is_finished = self.total is None or self.completed >= self.total
complete_style = console.get_style(
Expand Down
2 changes: 1 addition & 1 deletion rich/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ def process_response(self, value: str) -> bool:
result = IntPrompt.ask(
":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
)
if result >= 1 and result <= 10:
if 1 <= result <= 10:
break
print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
print(f"number={result}")
Expand Down
2 changes: 1 addition & 1 deletion rich/spinner.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def render(self, time: float) -> "RenderableType":
self.start_time = time

frame_no = ((time - self.start_time) * self.speed) / (
self.interval / 1000.0
self.interval / 1000
) + self.frame_no_offset
frame = Text(
self.frames[int(frame_no) % len(self.frames)], style=self.style or ""
Expand Down
14 changes: 3 additions & 11 deletions rich/syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,18 +492,10 @@ def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
line_no = 0
_line_start = line_start - 1 if line_start else 0

# Skip over tokens until line start
while line_no < _line_start:
try:
_token_type, token = next(tokens)
except StopIteration:
break
yield (token, None)
if token.endswith("\n"):
line_no += 1
# Generate spans until line end
for token_type, token in tokens:
yield (token, _get_theme_style(token_type))
# Skip over tokens until line start, then generate spans until line end
style = None if line_no < _line_start else _get_theme_style(token_type)
yield token, style
if token.endswith("\n"):
line_no += 1
if line_end and line_no >= line_end:
Expand Down
8 changes: 4 additions & 4 deletions tests/test_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_renderable_column():


def test_spinner_column():
time = 1.0
time = 1

def get_time():
nonlocal time
Expand All @@ -141,7 +141,7 @@ def get_time():
expected = "⣾"
assert str(result) == expected

time += 1.0
time += 1
column.spinner.update(speed=0.5)
result = column.render(task)
print(repr(result))
Expand Down Expand Up @@ -493,14 +493,14 @@ def test_reset() -> None:

def test_progress_max_refresh() -> None:
"""Test max_refresh argument."""
time = 0.0
time = 0

def get_time() -> float:
nonlocal time
try:
return time
finally:
time = time + 1.0
time += 1

console = Console(
color_system=None,
Expand Down
Loading