From a81ba837a969ccea97c3f12a680f5cc866602446 Mon Sep 17 00:00:00 2001 From: Sourcery AI Date: Tue, 25 Apr 2023 20:45:22 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- docs/conf.py | 37 ++++++--- examples.py | 67 ++++++++-------- progressbar/bar.py | 51 ++++-------- progressbar/multi.py | 7 +- progressbar/shortcuts.py | 3 +- progressbar/terminal/base.py | 5 +- progressbar/terminal/os_specific/windows.py | 5 +- progressbar/terminal/stream.py | 6 +- progressbar/utils.py | 49 ++++++------ progressbar/widgets.py | 86 ++++++--------------- setup.py | 2 +- tests/original_examples.py | 36 +++++---- tests/test_custom_widgets.py | 3 +- tests/test_end.py | 2 +- tests/test_failure.py | 2 +- tests/test_iterators.py | 10 +-- tests/test_monitor_progress.py | 10 +-- tests/test_multibar.py | 4 +- tests/test_stream.py | 8 +- tests/test_timed.py | 5 +- tests/test_unicode.py | 4 +- tests/test_unknown_length.py | 2 +- tests/test_widgets.py | 10 +-- 23 files changed, 179 insertions(+), 235 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 15d5ba34..df9ef70e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -61,10 +61,7 @@ # General information about the project. project = u'Progress Bar' project_slug = ''.join(project.capitalize().split()) -copyright = u'%s, %s' % ( - datetime.date.today().year, - metadata.__author__, -) +copyright = f'{datetime.date.today().year}, {metadata.__author__}' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -190,7 +187,7 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = '%sdoc' % project_slug +htmlhelp_basename = f'{project_slug}doc' # -- Options for LaTeX output -------------------------------------------- @@ -209,8 +206,13 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', '%s.tex' % project_slug, u'%s Documentation' % project, - metadata.__author__, 'manual'), + ( + 'index', + f'{project_slug}.tex', + f'{project} Documentation', + metadata.__author__, + 'manual', + ) ] # The name of an image file (relative to this directory) to place at the top of @@ -239,8 +241,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', project_slug.lower(), u'%s Documentation' % project, - [metadata.__author__], 1) + ( + 'index', + project_slug.lower(), + f'{project} Documentation', + [metadata.__author__], + 1, + ) ] # If true, show URL addresses after external links. @@ -253,9 +260,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', project_slug, u'%s Documentation' % project, - metadata.__author__, project_slug, 'One line description of project.', - 'Miscellaneous'), + ( + 'index', + project_slug, + f'{project} Documentation', + metadata.__author__, + project_slug, + 'One line description of project.', + 'Miscellaneous', + ) ] # Documents to append as an appendix to all manuals. diff --git a/examples.py b/examples.py index 1c033839..7fb48efe 100644 --- a/examples.py +++ b/examples.py @@ -39,19 +39,19 @@ def fast_example(): @example def shortcut_example(): - for i in progressbar.progressbar(range(10)): + for _ in progressbar.progressbar(range(10)): time.sleep(0.1) @example def prefixed_shortcut_example(): - for i in progressbar.progressbar(range(10), prefix='Hi: '): + for _ in progressbar.progressbar(range(10), prefix='Hi: '): time.sleep(0.1) @example def templated_shortcut_example(): - for i in progressbar.progressbar(range(10), suffix='{seconds_elapsed:.1}'): + for _ in progressbar.progressbar(range(10), suffix='{seconds_elapsed:.1}'): time.sleep(0.1) @@ -142,18 +142,14 @@ def multi_range_bar_example(): @example def multi_progress_bar_example(left=True): - jobs = [ - # Each job takes between 1 and 10 steps to complete - [0, random.randint(1, 10)] - for i in range(25) # 25 jobs total - ] + jobs = [[0, random.randint(1, 10)] for _ in range(25)] widgets = [ progressbar.Percentage(), ' ', progressbar.MultiProgressBar('jobs', fill_left=left), ] - max_value = sum([total for progress, total in jobs]) + max_value = sum(total for progress, total in jobs) with progressbar.ProgressBar(widgets=widgets, max_value=max_value) as bar: while True: incomplete_jobs = [ @@ -165,7 +161,7 @@ def multi_progress_bar_example(left=True): break which = random.choice(incomplete_jobs) jobs[which][0] += 1 - progress = sum([progress for progress, total in jobs]) + progress = sum(progress for progress, total in jobs) bar.update(progress, jobs=jobs, force=True) time.sleep(0.02) @@ -181,10 +177,10 @@ def granular_progress_example(): progressbar.GranularBar(markers=" ⡀⡄⡆⡇⣇⣧⣷⣿", left='', right='|'), progressbar.GranularBar(markers=" .oO", left='', right=''), ] - for i in progressbar.progressbar(list(range(100)), widgets=widgets): + for _ in progressbar.progressbar(list(range(100)), widgets=widgets): time.sleep(0.03) - for i in progressbar.progressbar(iter(range(100)), widgets=widgets): + for _ in progressbar.progressbar(iter(range(100)), widgets=widgets): time.sleep(0.03) @@ -216,17 +212,20 @@ def file_transfer_example(): @example def custom_file_transfer_example(): + + + class CrazyFileTransferSpeed(progressbar.FileTransferSpeed): ''' It's bigger between 45 and 80 percent ''' def update(self, bar): if 45 < bar.percentage() < 80: - return 'Bigger Now ' + progressbar.FileTransferSpeed.update( - self, bar) + return f'Bigger Now {progressbar.FileTransferSpeed.update(self, bar)}' else: return progressbar.FileTransferSpeed.update(self, bar) + widgets = [ CrazyFileTransferSpeed(), ' <<<', progressbar.Bar(), '>>> ', @@ -300,7 +299,7 @@ def basic_progress(): def progress_with_automatic_max(): # Progressbar can guess max_value automatically. bar = progressbar.ProgressBar() - for i in bar(range(8)): + for _ in bar(range(8)): time.sleep(0.1) @@ -308,7 +307,7 @@ def progress_with_automatic_max(): def progress_with_unavailable_max(): # Progressbar can't guess max_value. bar = progressbar.ProgressBar(max_value=8) - for i in bar((i for i in range(8))): + for _ in bar(iter(range(8))): time.sleep(0.1) @@ -316,7 +315,7 @@ def progress_with_unavailable_max(): def animated_marker(): bar = progressbar.ProgressBar( widgets=['Working: ', progressbar.AnimatedMarker()]) - for i in bar((i for i in range(5))): + for _ in bar(iter(range(5))): time.sleep(0.1) @@ -327,7 +326,7 @@ def filling_bar_animated_marker(): marker=progressbar.AnimatedMarker(fill='#'), ), ]) - for i in bar(range(15)): + for _ in bar(range(15)): time.sleep(0.1) @@ -336,7 +335,7 @@ def counter_and_timer(): widgets = ['Processed: ', progressbar.Counter('Counter: %(value)05d'), ' lines (', progressbar.Timer(), ')'] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(15))): + for _ in bar(iter(range(15))): time.sleep(0.1) @@ -345,7 +344,7 @@ def format_label(): widgets = [progressbar.FormatLabel( 'Processed: %(value)d lines (in: %(elapsed)s)')] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(15))): + for _ in bar(iter(range(15))): time.sleep(0.1) @@ -353,7 +352,7 @@ def format_label(): def animated_balloons(): widgets = ['Balloon: ', progressbar.AnimatedMarker(markers='.oO@* ')] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(24))): + for _ in bar(iter(range(24))): time.sleep(0.1) @@ -363,7 +362,7 @@ def animated_arrows(): try: widgets = ['Arrows: ', progressbar.AnimatedMarker(markers='←↖↑↗→↘↓↙')] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(24))): + for _ in bar(iter(range(24))): time.sleep(0.1) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -375,7 +374,7 @@ def animated_filled_arrows(): try: widgets = ['Arrows: ', progressbar.AnimatedMarker(markers='◢◣◤◥')] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(24))): + for _ in bar(iter(range(24))): time.sleep(0.1) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -387,7 +386,7 @@ def animated_wheels(): try: widgets = ['Wheels: ', progressbar.AnimatedMarker(markers='◐◓◑◒')] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(24))): + for _ in bar(iter(range(24))): time.sleep(0.1) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -400,7 +399,7 @@ def format_label_bouncer(): progressbar.BouncingBar(), ] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(100))): + for _ in bar(iter(range(100))): time.sleep(0.01) @@ -410,7 +409,7 @@ def format_label_rotating_bouncer(): progressbar.BouncingBar(marker=progressbar.RotatingMarker())] bar = progressbar.ProgressBar(widgets=widgets) - for i in bar((i for i in range(18))): + for _ in bar(iter(range(18))): time.sleep(0.1) @@ -488,7 +487,7 @@ def incrementing_bar(): progressbar.Percentage(), progressbar.Bar(), ], max_value=10).start() - for i in range(10): + for _ in range(10): # do something time.sleep(0.1) bar += 1 @@ -545,7 +544,7 @@ def adaptive_eta_without_value_change(): progressbar.AdaptiveTransferSpeed(), ], max_value=2, poll_interval=0.0001) bar.start() - for i in range(100): + for _ in range(100): bar.update(1) time.sleep(0.1) bar.finish() @@ -556,7 +555,7 @@ def iterator_with_max_value(): # Testing using progressbar as an iterator with a max value bar = progressbar.ProgressBar() - for n in bar(iter(range(100)), 100): + for _ in bar(iter(range(100)), 100): # iter range is a way to get an iterator in both python 2 and 3 pass @@ -622,12 +621,12 @@ def user_variables(): num_subtasks = sum(len(x) for x in tasks.values()) with progressbar.ProgressBar( - prefix='{variables.task} >> {variables.subtask}', - variables={'task': '--', 'subtask': '--'}, - max_value=10 * num_subtasks) as bar: + prefix='{variables.task} >> {variables.subtask}', + variables={'task': '--', 'subtask': '--'}, + max_value=10 * num_subtasks) as bar: for tasks_name, subtasks in tasks.items(): for subtask_name in subtasks: - for i in range(10): + for _ in range(10): bar.update(bar.value + 1, task=tasks_name, subtask=subtask_name) time.sleep(0.1) @@ -656,7 +655,7 @@ def format_custom_text(): @example def simple_api_example(): bar = progressbar.ProgressBar(widget_kwargs=dict(fill='█')) - for i in bar(range(200)): + for _ in bar(range(200)): time.sleep(0.02) diff --git a/progressbar/bar.py b/progressbar/bar.py index d9616f68..01831fd6 100644 --- a/progressbar/bar.py +++ b/progressbar/bar.py @@ -93,10 +93,7 @@ def get_last_update_time(self) -> types.Optional[datetime]: return None def set_last_update_time(self, value: types.Optional[datetime]): - if value: - self._last_update_time = time.mktime(value.timetuple()) - else: - self._last_update_time = None + self._last_update_time = time.mktime(value.timetuple()) if value else None last_update_time = property(get_last_update_time, set_last_update_time) @@ -222,10 +219,7 @@ def __init__( enable_colors = terminal.ColorSupport.XTERM_256 elif enable_colors is False: enable_colors = terminal.ColorSupport.NONE - elif isinstance(enable_colors, terminal.ColorSupport): - # `enable_colors` is already a valid value - pass - else: + elif not isinstance(enable_colors, terminal.ColorSupport): raise ValueError(f'Invalid color support value: {enable_colors}') self.enable_colors = enable_colors @@ -242,11 +236,7 @@ def update(self, *args, **kwargs): if not self.enable_colors: line = utils.no_color(line) - if self.line_breaks: - line = line.rstrip() + '\n' - else: - line = '\r' + line - + line = line.rstrip() + '\n' if self.line_breaks else '\r' + line try: # pragma: no cover self.fd.write(line) except UnicodeEncodeError: # pragma: no cover @@ -530,13 +520,10 @@ def __init__( ) poll_interval = kwargs.get('poll') - if max_value: - # mypy doesn't understand that a boolean check excludes - # `UnknownLength` - if min_value > max_value: # type: ignore - raise ValueError( - 'Max value needs to be bigger than the min ' 'value' - ) + if max_value and min_value > max_value: + raise ValueError( + 'Max value needs to be bigger than the min ' 'value' + ) self.min_value = min_value # Legacy issue, `max_value` can be `None` before execution. After # that it either has a value or is `UnknownLength` @@ -589,9 +576,11 @@ def __init__( # A dictionary of names that can be used by Variable and FormatWidget self.variables = utils.AttributeDict(variables or {}) for widget in self.widgets: - if isinstance(widget, widgets_module.VariableMixin): - if widget.name not in self.variables: - self.variables[widget.name] = None + if ( + isinstance(widget, widgets_module.VariableMixin) + and widget.name not in self.variables + ): + self.variables[widget.name] = None @property def dynamic_messages(self): # pragma: no cover @@ -611,7 +600,7 @@ def init(self): self.start_time = None self.updates = 0 self.end_time = None - self.extra = dict() + self.extra = {} self._last_update_timer = timeit.default_timer() @property @@ -734,7 +723,7 @@ def default_widgets(self): widgets.Percentage(**self.widget_kwargs), ' ', widgets.SimpleProgress( - format='(%s)' % widgets.SimpleProgress.DEFAULT_FORMAT, + format=f'({widgets.SimpleProgress.DEFAULT_FORMAT})', **self.widget_kwargs, ), ' ', @@ -773,11 +762,7 @@ def __iter__(self): def __next__(self): try: - if self._iterable is None: # pragma: no cover - value = self.value - else: - value = next(self._iterable) - + value = self.value if self._iterable is None else next(self._iterable) if self.start_time is None: self.start() else: @@ -853,14 +838,12 @@ def update(self, value=None, force=False, **kwargs): pass elif self.min_value > value: # type: ignore raise ValueError( - 'Value %s is too small. Should be between %s and %s' - % (value, self.min_value, self.max_value) + f'Value {value} is too small. Should be between {self.min_value} and {self.max_value}' ) elif self.max_value < value: # type: ignore if self.max_error: raise ValueError( - 'Value %s is too large. Should be between %s and %s' - % (value, self.min_value, self.max_value) + f'Value {value} is too large. Should be between {self.min_value} and {self.max_value}' ) else: value = self.max_value diff --git a/progressbar/multi.py b/progressbar/multi.py index 7922a812..087083dc 100644 --- a/progressbar/multi.py +++ b/progressbar/multi.py @@ -187,10 +187,9 @@ def update(force=True, write=True): # Force update to get the finished format update(write=False) - if self.remove_finished: - if expired >= self._finished_at[bar_]: - del self[bar_.label] - continue + if self.remove_finished and expired >= self._finished_at[bar_]: + del self[bar_.label] + continue if not self.show_finished: continue diff --git a/progressbar/shortcuts.py b/progressbar/shortcuts.py index 9e1502dd..eb30b715 100644 --- a/progressbar/shortcuts.py +++ b/progressbar/shortcuts.py @@ -19,5 +19,4 @@ def progressbar( **kwargs ) - for result in progressbar(iterator): - yield result + yield from progressbar(iterator) diff --git a/progressbar/terminal/base.py b/progressbar/terminal/base.py index 469e37fa..8df2e75a 100644 --- a/progressbar/terminal/base.py +++ b/progressbar/terminal/base.py @@ -213,10 +213,7 @@ def __call__(self, stream): res = tuple(int(item) if item.isdigit() else item for item in res) - if len(res) == 1: - return res[0] - - return res + return res[0] if len(res) == 1 else res def row(self, stream): row, _ = self(stream) diff --git a/progressbar/terminal/os_specific/windows.py b/progressbar/terminal/os_specific/windows.py index 6084f3b1..c611d417 100644 --- a/progressbar/terminal/os_specific/windows.py +++ b/progressbar/terminal/os_specific/windows.py @@ -124,7 +124,4 @@ def getch(): ) char = lpBuffer[1].Event.KeyEvent.uChar.AsciiChar.decode('ascii') - if char == '\x00': - return None - - return char + return None if char == '\x00' else char diff --git a/progressbar/terminal/stream.py b/progressbar/terminal/stream.py index ecf8a6d3..b4c3f233 100644 --- a/progressbar/terminal/stream.py +++ b/progressbar/terminal/stream.py @@ -111,11 +111,7 @@ def write(self, data): self.line = data def truncate(self, __size: int | None = None) -> int: - if __size is None: - self.line = '' - else: - self.line = self.line[:__size] - + self.line = '' if __size is None else self.line[:__size] return len(self.line) def writelines(self, __lines: Iterable[str]) -> None: diff --git a/progressbar/utils.py b/progressbar/utils.py index 256dd98c..d1d0d00b 100644 --- a/progressbar/utils.py +++ b/progressbar/utils.py @@ -39,7 +39,7 @@ 'tmux', 'vt(10[02]|220|320)', ) -ANSI_TERM_RE = re.compile('^({})'.format('|'.join(ANSI_TERMS)), re.IGNORECASE) +ANSI_TERM_RE = re.compile(f"^({'|'.join(ANSI_TERMS)})", re.IGNORECASE) def is_ansi_terminal( @@ -231,8 +231,7 @@ def flush(self) -> None: self.buffer.flush() def _flush(self) -> None: - value = self.buffer.getvalue() - if value: + if value := self.buffer.getvalue(): self.flush() self.target.write(value) self.buffer.seek(0) @@ -438,27 +437,25 @@ def needs_clear(self) -> bool: # pragma: no cover return stderr_needs_clear or stdout_needs_clear def flush(self) -> None: - if self.wrapped_stdout: # pragma: no branch - if isinstance(self.stdout, WrappingIO): # pragma: no branch - try: - self.stdout._flush() - except io.UnsupportedOperation: # pragma: no cover - self.wrapped_stdout = False - logger.warning( - 'Disabling stdout redirection, %r is not seekable', - sys.stdout, - ) - - if self.wrapped_stderr: # pragma: no branch - if isinstance(self.stderr, WrappingIO): # pragma: no branch - try: - self.stderr._flush() - except io.UnsupportedOperation: # pragma: no cover - self.wrapped_stderr = False - logger.warning( - 'Disabling stderr redirection, %r is not seekable', - sys.stderr, - ) + if self.wrapped_stdout and isinstance(self.stdout, WrappingIO): + try: + self.stdout._flush() + except io.UnsupportedOperation: # pragma: no cover + self.wrapped_stdout = False + logger.warning( + 'Disabling stdout redirection, %r is not seekable', + sys.stdout, + ) + + if self.wrapped_stderr and isinstance(self.stderr, WrappingIO): + try: + self.stderr._flush() + except io.UnsupportedOperation: # pragma: no cover + self.wrapped_stderr = False + logger.warning( + 'Disabling stderr redirection, %r is not seekable', + sys.stderr, + ) def excepthook(self, exc_type, exc_value, exc_traceback): self.original_excepthook(exc_type, exc_value, exc_traceback) @@ -515,7 +512,7 @@ def __getattr__(self, name: str) -> int: if name in self: return self[name] else: - raise AttributeError("No such attribute: " + name) + raise AttributeError(f"No such attribute: {name}") def __setattr__(self, name: str, value: int) -> None: self[name] = value @@ -524,7 +521,7 @@ def __delattr__(self, name: str) -> None: if name in self: del self[name] else: - raise AttributeError("No such attribute: " + name) + raise AttributeError(f"No such attribute: {name}") logger = logging.getLogger(__name__) diff --git a/progressbar/widgets.py b/progressbar/widgets.py index fc09f5ba..199e3fab 100644 --- a/progressbar/widgets.py +++ b/progressbar/widgets.py @@ -138,10 +138,7 @@ def __call__( '''Formats the widget into a string''' format = self.get_format(progress, data, format) try: - if self.new_style: - return format.format(**data) - else: - return format % data + return format.format(**data) if self.new_style else format % data except (TypeError, KeyError): print('Error while formatting %r' % format, file=sys.stderr) pprint.pprint(data, stream=sys.stderr) @@ -234,11 +231,7 @@ def uses_colors(self): if value is not None: return True - for key, value in self._fixed_colors.items(): - if value is not None: - return True - - return False + return any(value is not None for key, value in self._fixed_colors.items()) def _apply_colors(self, text: str, data: Data) -> str: if self.uses_colors: @@ -332,10 +325,7 @@ def __call__( ): for name, (key, transform) in self.mapping.items(): try: - if transform is None: - data[name] = data[key] - else: - data[name] = transform(data[key]) + data[name] = data[key] if transform is None else transform(data[key]) except (KeyError, ValueError, IndexError): # pragma: no cover pass @@ -401,10 +391,10 @@ def __init__( TimeSensitiveWidgetBase.__init__(self, **kwargs) def get_sample_times(self, progress: ProgressBarMixinBase, data: Data): - return progress.extra.setdefault(self.key_prefix + 'sample_times', []) + return progress.extra.setdefault(f'{self.key_prefix}sample_times', []) def get_sample_values(self, progress: ProgressBarMixinBase, data: Data): - return progress.extra.setdefault(self.key_prefix + 'sample_values', []) + return progress.extra.setdefault(f'{self.key_prefix}sample_values', []) def __call__( self, progress: ProgressBarMixinBase, data: Data, delta: bool = False @@ -412,11 +402,7 @@ def __call__( sample_times = self.get_sample_times(progress, data) sample_values = self.get_sample_values(progress, data) - if sample_times: - sample_time = sample_times[-1] - else: - sample_time = datetime.datetime.min - + sample_time = sample_times[-1] if sample_times else datetime.datetime.min if progress.last_update_time - sample_time > self.INTERVAL: # Add a sample but limit the size to `num_samples` sample_times.append(progress.last_update_time) @@ -432,20 +418,15 @@ def __call__( ): sample_times.pop(0) sample_values.pop(0) - else: - if len(sample_times) > self.samples: - sample_times.pop(0) - sample_values.pop(0) + elif len(sample_times) > self.samples: + sample_times.pop(0) + sample_values.pop(0) - if delta: - delta_time = sample_times[-1] - sample_times[0] - delta_value = sample_values[-1] - sample_values[0] - if delta_time: - return delta_time, delta_value - else: - return None, None - else: + if not delta: return sample_times, sample_values + delta_time = sample_times[-1] - sample_times[0] + delta_value = sample_values[-1] - sample_values[0] + return (delta_time, delta_value) if delta_time else (None, None) class ETA(Timer): @@ -474,15 +455,12 @@ def _calculate_eta( self, progress: ProgressBarMixinBase, data: Data, value, elapsed ): '''Updates the widget to show the ETA or total time when finished.''' - if elapsed: - # The max() prevents zero division errors - per_item = elapsed.total_seconds() / max(value, 1e-6) - remaining = progress.max_value - data['value'] - eta_seconds = remaining * per_item - else: - eta_seconds = 0 + if not elapsed: + return 0 - return eta_seconds + # The max() prevents zero division errors + per_item = elapsed.total_seconds() / max(value, 1e-6) + return (progress.max_value - data['value']) * per_item def __call__( self, @@ -824,24 +802,15 @@ class SimpleProgress(FormatWidgetMixin, ColoredMixin, WidgetBase): def __init__(self, format=DEFAULT_FORMAT, **kwargs): FormatWidgetMixin.__init__(self, format=format, **kwargs) WidgetBase.__init__(self, format=format, **kwargs) - self.max_width_cache = dict() - self.max_width_cache['default'] = self.max_width or 0 + self.max_width_cache = {'default': self.max_width or 0} def __call__( self, progress: ProgressBarMixinBase, data: Data, format=None ): # If max_value is not available, display N/A - if data.get('max_value'): - data['max_value_s'] = data['max_value'] - else: - data['max_value_s'] = 'N/A' - + data['max_value_s'] = data['max_value'] if data.get('max_value') else 'N/A' # if value is not available it's the zeroth iteration - if data.get('value'): - data['value_s'] = data['value'] - else: - data['value_s'] = 0 - + data['value_s'] = data['value'] if data.get('value') else 0 formatted = FormatWidgetMixin.__call__( self, progress, data, format=format ) @@ -858,12 +827,11 @@ def __call__( continue temporary_data['value'] = value - width = progress.custom_len( + if width := progress.custom_len( FormatWidgetMixin.__call__( self, progress, temporary_data, format=format ) - ) - if width: # pragma: no branch + ): max_width = max(max_width or 0, width) self.max_width_cache[key] = max_width @@ -1131,10 +1099,7 @@ def get_values(self, progress: ProgressBarMixinBase, data: Data): value = float(progress_value) / float(progress_max) if not 0 <= value <= 1: - raise ValueError( - 'Range value needs to be in the range [0..1], got %s' - % value - ) + raise ValueError(f'Range value needs to be in the range [0..1], got {value}') range_ = value * (len(ranges) - 1) pos = int(range_) @@ -1220,8 +1185,7 @@ def __call__( marker = self.markers[-1] * int(num_chars) - marker_idx = int((num_chars % 1) * (len(self.markers) - 1)) - if marker_idx: + if marker_idx := int((num_chars % 1) * (len(self.markers) - 1)): marker += self.markers[marker_idx] marker = converters.to_unicode(marker) diff --git a/setup.py b/setup.py index 850df2de..ab559f5c 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ install_reqs = [] if sys.argv[-1] == 'info': for k, v in about.items(): - print('%s: %s' % (k, v)) + print(f'{k}: {v}') sys.exit() if os.path.isfile('README.rst'): diff --git a/tests/original_examples.py b/tests/original_examples.py index 2e521e9d..f85c1311 100644 --- a/tests/original_examples.py +++ b/tests/original_examples.py @@ -45,14 +45,18 @@ def example1(): @example def example2(): + + + class CrazyFileTransferSpeed(FileTransferSpeed): """It's bigger between 45 and 80 percent.""" def update(self, pbar): if 45 < pbar.percentage() < 80: - return 'Bigger Now ' + FileTransferSpeed.update(self,pbar) + return f'Bigger Now {FileTransferSpeed.update(self, pbar)}' else: return FileTransferSpeed.update(self,pbar) + widgets = [CrazyFileTransferSpeed(),' <<<', Bar(), '>>> ', Percentage(),' ', ETA()] pbar = ProgressBar(widgets=widgets, maxval=10000) @@ -103,40 +107,40 @@ def example6(): @example def example7(): pbar = ProgressBar() # Progressbar can guess maxval automatically. - for i in pbar(range(80)): + for _ in pbar(range(80)): time.sleep(0.01) @example def example8(): pbar = ProgressBar(maxval=80) # Progressbar can't guess maxval. - for i in pbar((i for i in range(80))): + for _ in pbar(iter(range(80))): time.sleep(0.01) @example def example9(): pbar = ProgressBar(widgets=['Working: ', AnimatedMarker()]) - for i in pbar((i for i in range(50))): + for _ in pbar(iter(range(50))): time.sleep(.08) @example def example10(): widgets = ['Processed: ', Counter(), ' lines (', Timer(), ')'] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(150))): + for _ in pbar(iter(range(150))): time.sleep(0.1) @example def example11(): widgets = [FormatLabel('Processed: %(value)d lines (in: %(elapsed)s)')] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(150))): + for _ in pbar(iter(range(150))): time.sleep(0.1) @example def example12(): widgets = ['Balloon: ', AnimatedMarker(markers='.oO@* ')] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(24))): + for _ in pbar(iter(range(24))): time.sleep(0.3) @example @@ -145,7 +149,7 @@ def example13(): try: widgets = ['Arrows: ', AnimatedMarker(markers='←↖↑↗→↘↓↙')] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(24))): + for _ in pbar(iter(range(24))): time.sleep(0.3) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -155,7 +159,7 @@ def example14(): try: widgets = ['Arrows: ', AnimatedMarker(markers='◢◣◤◥')] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(24))): + for _ in pbar(iter(range(24))): time.sleep(0.3) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -165,7 +169,7 @@ def example15(): try: widgets = ['Wheels: ', AnimatedMarker(markers='◐◓◑◒')] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(24))): + for _ in pbar(iter(range(24))): time.sleep(0.3) except UnicodeError: sys.stdout.write('Unicode error: skipping example') @@ -173,7 +177,7 @@ def example15(): def example16(): widgets = [FormatLabel('Bouncer: value %(value)d - '), BouncingBar()] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(180))): + for _ in pbar(iter(range(180))): time.sleep(0.05) @example @@ -182,7 +186,7 @@ def example17(): BouncingBar(marker=RotatingMarker())] pbar = ProgressBar(widgets=widgets) - for i in pbar((i for i in range(180))): + for _ in pbar(iter(range(180))): time.sleep(0.05) @example @@ -200,10 +204,10 @@ def example18(): @example def example19(): - pbar = ProgressBar() - for i in pbar([]): - pass - pbar.finish() + pbar = ProgressBar() + for _ in pbar([]): + pass + pbar.finish() @example def example20(): diff --git a/tests/test_custom_widgets.py b/tests/test_custom_widgets.py index e757ded5..22b1e66b 100644 --- a/tests/test_custom_widgets.py +++ b/tests/test_custom_widgets.py @@ -10,8 +10,7 @@ class CrazyFileTransferSpeed(progressbar.FileTransferSpeed): def update(self, pbar): if 45 < pbar.percentage() < 80: - return 'Bigger Now ' + progressbar.FileTransferSpeed.update(self, - pbar) + return f'Bigger Now {progressbar.FileTransferSpeed.update(self, pbar)}' else: return progressbar.FileTransferSpeed.update(self, pbar) diff --git a/tests/test_end.py b/tests/test_end.py index 75d45723..42842a2e 100644 --- a/tests/test_end.py +++ b/tests/test_end.py @@ -37,7 +37,7 @@ def test_end_100(monkeypatch): max_value=103, ) - for x in range(0, 102): + for x in range(102): p.update(x) data = p.data() diff --git a/tests/test_failure.py b/tests/test_failure.py index a389da4b..204053c8 100644 --- a/tests/test_failure.py +++ b/tests/test_failure.py @@ -64,7 +64,7 @@ def test_one_max_value(): def test_changing_max_value(): '''Changing max_value? No problem''' p = progressbar.ProgressBar(max_value=10)(range(20), max_value=20) - for i in p: + for _ in p: time.sleep(1) diff --git a/tests/test_iterators.py b/tests/test_iterators.py index b32c529e..218f048c 100644 --- a/tests/test_iterators.py +++ b/tests/test_iterators.py @@ -6,14 +6,14 @@ def test_list(): '''Progressbar can guess max_value automatically.''' p = progressbar.ProgressBar() - for i in p(range(10)): + for _ in p(range(10)): time.sleep(0.001) def test_iterator_with_max_value(): '''Progressbar can't guess max_value.''' p = progressbar.ProgressBar(max_value=10) - for i in p((i for i in range(10))): + for _ in p(iter(range(10))): time.sleep(0.001) @@ -21,7 +21,7 @@ def test_iterator_without_max_value_error(): '''Progressbar can't guess max_value.''' p = progressbar.ProgressBar() - for i in p((i for i in range(10))): + for _ in p(iter(range(10))): time.sleep(0.001) assert p.max_value is progressbar.UnknownLength @@ -35,7 +35,7 @@ def test_iterator_without_max_value(): progressbar.BouncingBar(), progressbar.BouncingBar(marker=progressbar.RotatingMarker()), ]) - for i in p((i for i in range(10))): + for _ in p(iter(range(10))): time.sleep(0.001) @@ -43,7 +43,7 @@ def test_iterator_with_incorrect_max_value(): '''Progressbar can't guess max_value.''' p = progressbar.ProgressBar(max_value=10) with pytest.raises(ValueError): - for i in p((i for i in range(20))): + for _ in p(iter(range(20))): time.sleep(0.001) diff --git a/tests/test_monitor_progress.py b/tests/test_monitor_progress.py index 5dd6f5ee..f1e843db 100644 --- a/tests/test_monitor_progress.py +++ b/tests/test_monitor_progress.py @@ -90,12 +90,10 @@ def test_generator_example(testdir): result.stderr.lines = [l for l in result.stderr.lines if l.strip()] pprint.pprint(result.stderr.lines, width=70) - lines = [] - for i in range(9): - lines.append( - r'[/\\|\-]\s+\|\s*#\s*\| %(i)d Elapsed Time: \d:00:%(i)02d' % - dict(i=i)) - + lines = [ + r'[/\\|\-]\s+\|\s*#\s*\| %(i)d Elapsed Time: \d:00:%(i)02d' % dict(i=i) + for i in range(9) + ] result.stderr.re_match_lines(lines) diff --git a/tests/test_multibar.py b/tests/test_multibar.py index 4865ae3e..11c5f3e8 100644 --- a/tests/test_multibar.py +++ b/tests/test_multibar.py @@ -86,11 +86,11 @@ def test_multibar_sorting(sort_key): with progressbar.MultiBar() as multibar: for i in range(bars): - label = 'bar {}'.format(i) + label = f'bar {i}' multibar[label] = progressbar.ProgressBar(max_value=N) for bar in multibar.values(): - for j in bar(range(N)): + for _ in bar(range(N)): assert bar.started() time.sleep(0.002) diff --git a/tests/test_stream.py b/tests/test_stream.py index 6dcfcf7c..abb9f48c 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -6,7 +6,7 @@ def test_nowrap(): # Make sure we definitely unwrap - for i in range(5): + for _ in range(5): progressbar.streams.unwrap(stderr=True, stdout=True) stdout = sys.stdout @@ -23,13 +23,13 @@ def test_nowrap(): assert stderr == sys.stderr # Make sure we definitely unwrap - for i in range(5): + for _ in range(5): progressbar.streams.unwrap(stderr=True, stdout=True) def test_wrap(): # Make sure we definitely unwrap - for i in range(5): + for _ in range(5): progressbar.streams.unwrap(stderr=True, stdout=True) stdout = sys.stdout @@ -50,7 +50,7 @@ def test_wrap(): assert stderr == sys.stderr # Make sure we definitely unwrap - for i in range(5): + for _ in range(5): progressbar.streams.unwrap(stderr=True, stdout=True) diff --git a/tests/test_timed.py b/tests/test_timed.py index 6753f537..b7c3170b 100644 --- a/tests/test_timed.py +++ b/tests/test_timed.py @@ -57,7 +57,7 @@ def test_adaptive_eta(): ) p.start() - for i in range(20): + for _ in range(20): p.update(1) time.sleep(0.001) p.finish() @@ -160,8 +160,7 @@ def test_eta_not_available(): ETAs should not raise exceptions. """ def gen(): - for x in range(200): - yield x + yield from range(200) widgets = [progressbar.AdaptiveETA(), progressbar.ETA()] diff --git a/tests/test_unicode.py b/tests/test_unicode.py index 3b8e4aec..7ef6bc83 100644 --- a/tests/test_unicode.py +++ b/tests/test_unicode.py @@ -19,11 +19,11 @@ def test_markers(name, markers, as_unicode): markers = converters.to_str(markers) widgets = [ - '%s: ' % name.capitalize(), + f'{name.capitalize()}: ', progressbar.AnimatedMarker(markers=markers), ] bar = progressbar.ProgressBar(widgets=widgets) bar._MINIMUM_UPDATE_INTERVAL = 1e-12 - for i in bar((i for i in range(24))): + for _ in bar(iter(range(24))): time.sleep(0.001) diff --git a/tests/test_unknown_length.py b/tests/test_unknown_length.py index fe08e209..8b2cbdfc 100644 --- a/tests/test_unknown_length.py +++ b/tests/test_unknown_length.py @@ -25,4 +25,4 @@ def test_unknown_length_at_start(): pb2 = progressbar.ProgressBar().start(max_value=progressbar.UnknownLength) for w in pb2.widgets: print(type(w), repr(w)) - assert any([isinstance(w, progressbar.Bar) for w in pb2.widgets]) + assert any(isinstance(w, progressbar.Bar) for w in pb2.widgets) diff --git a/tests/test_widgets.py b/tests/test_widgets.py index a38574da..23044f23 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -57,12 +57,12 @@ def test_widgets_large_values(max_value): def test_format_widget(): - widgets = [] - for mapping in progressbar.FormatLabel.mapping: - widgets.append(progressbar.FormatLabel('%%(%s)r' % mapping)) - + widgets = [ + progressbar.FormatLabel('%%(%s)r' % mapping) + for mapping in progressbar.FormatLabel.mapping + ] p = progressbar.ProgressBar(widgets=widgets) - for i in p(range(10)): + for _ in p(range(10)): time.sleep(1)