Skip to content

Commit

Permalink
Simplify and upgrade with ruff rules SIM and UP
Browse files Browse the repository at this point in the history
  • Loading branch information
cclauss committed Apr 28, 2024
1 parent 8f3b470 commit 373541d
Show file tree
Hide file tree
Showing 21 changed files with 77 additions and 179 deletions.
15 changes: 7 additions & 8 deletions doc/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# pyperf documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 1 15:28:03 2016.
Expand Down Expand Up @@ -42,9 +41,9 @@
master_doc = 'index'

# General information about the project.
project = u'pyperf'
copyright = u'2016, Victor Stinner'
author = u'Victor Stinner'
project = 'pyperf'
copyright = '2016, Victor Stinner'
author = 'Victor Stinner'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -216,8 +215,8 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'pyperf.tex', u'pyperf Documentation',
u'Victor Stinner', 'manual'),
(master_doc, 'pyperf.tex', 'pyperf Documentation',
'Victor Stinner', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -246,7 +245,7 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pyperf', u'pyperf Documentation',
(master_doc, 'pyperf', 'pyperf Documentation',
[author], 1)
]

Expand All @@ -260,7 +259,7 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'pyperf', u'pyperf Documentation',
(master_doc, 'pyperf', 'pyperf Documentation',
author, 'pyperf', 'One line description of project.',
'Miscellaneous'),
]
Expand Down
4 changes: 1 addition & 3 deletions doc/examples/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,14 @@ def plot_bench(args, bench):
values = []
width = None
for run_index, run in enumerate(bench.get_runs()):
index = 0
x = []
y = []
run_values = run.values
if args.skip:
run_values = run_values[args.skip:]
for value in run_values:
for index, value in enumerate(run_values):
x.append(index)
y.append(value)
index += 1
plt.plot(x, y, color='blue')
values.extend(run_values)
width = len(run_values)
Expand Down
10 changes: 2 additions & 8 deletions pyperf/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,14 +330,8 @@ def group_by_name(self):
for suite in self.suites:
benchmark = suite.get_benchmark(name)
filename = format_filename(suite.filename)
if show_name:
if not show_filename:
title = name
else:
# name is displayed in the group title
title = filename
else:
title = None
# name is displayed in the group title
title = (filename if show_filename else name) if show_name else None
benchmarks.append(GroupItem(benchmark, title, filename))

is_last = (index == (len(names) - 1))
Expand Down
26 changes: 7 additions & 19 deletions pyperf/_bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def method(self):
return method


class Run(object):
class Run:
# Run is immutable, so it can be shared/exchanged between two benchmarks

__slots__ = ('_warmups', '_values', '_metadata')
Expand Down Expand Up @@ -131,10 +131,7 @@ def __init__(self, values, warmups=None,
def _replace(self, values=None, warmups=True, metadata=None):
if values is None:
values = self._values
if warmups:
warmups = self._warmups
else:
warmups = None
warmups = self._warmups if warmups else None
if metadata is None:
# share metadata dict since Run metadata is immutable
metadata = self._metadata
Expand Down Expand Up @@ -286,10 +283,7 @@ def _extract_metadata(self, name):
raise KeyError("run has no metadata %r" % name)

info = get_metadata_info(name)
if info.unit:
metadata = dict(self._metadata, unit=info.unit)
else:
metadata = None
metadata = dict(self._metadata, unit=info.unit) if info.unit else None

if not isinstance(value, NUMBER_TYPES):
raise TypeError("metadata %r value is not an integer: got %s"
Expand Down Expand Up @@ -319,7 +313,7 @@ def _update_metadata(self, metadata):
return self._replace(metadata=metadata2)


class Benchmark(object):
class Benchmark:
def __init__(self, runs):
self._runs = [] # list of Run objects
self._clear_runs_cache()
Expand Down Expand Up @@ -627,7 +621,7 @@ def update_metadata(self, metadata):
self._replace_runs(new_runs)


class BenchmarkSuite(object):
class BenchmarkSuite:
def __init__(self, benchmarks, filename=None):
if not benchmarks:
raise ValueError("benchmarks must be a non-empty "
Expand Down Expand Up @@ -724,10 +718,7 @@ def _json_load(cls, filename, data):

@staticmethod
def _load_open(filename):
if isinstance(filename, bytes):
suffix = b'.gz'
else:
suffix = u'.gz'
suffix = b'.gz' if isinstance(filename, bytes) else '.gz'

if filename.endswith(suffix):
# Use lazy import to limit imports on 'import pyperf'
Expand Down Expand Up @@ -767,10 +758,7 @@ def loads(cls, string):

@staticmethod
def _dump_open(filename, replace):
if isinstance(filename, bytes):
suffix = b'.gz'
else:
suffix = u'.gz'
suffix = b'.gz' if isinstance(filename, bytes) else '.gz'

if not replace and os.path.exists(filename):
raise OSError(errno.EEXIST, "File already exists")
Expand Down
51 changes: 11 additions & 40 deletions pyperf/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ def format_title(title, level=1, lines=None):
empty_line(lines)

lines.append(title)
if level == 1:
char = '='
else:
char = '-'
char = '=' if level == 1 else '-'
lines.append(char * len(title))
return lines

Expand Down Expand Up @@ -77,10 +74,7 @@ def format_run(bench, run_index, run, common_metadata=None, raw=False,
loops = run._get_calibration_loops()
action = 'calibrate the number of loops: %s' % format_number(loops)
lines.append("Run %s: %s" % (run_index, action))
if raw:
name = 'raw calibrate'
else:
name = 'calibrate'
name = 'raw calibrate' if raw else 'calibrate'
unit = bench.get_unit()
format_value = bench.format_value
for index, warmup in enumerate(run.warmups, 1):
Expand Down Expand Up @@ -131,17 +125,11 @@ def format_run(bench, run_index, run, common_metadata=None, raw=False,
lines.append("Run %s:" % run_index)

if warmups and show_warmup:
if raw:
name = 'raw warmup'
else:
name = 'warmup'
name = 'raw warmup' if raw else 'warmup'
for index, warmup in enumerate(warmups, 1):
lines.append('- %s %s: %s' % (name, index, warmup))

if raw:
name = 'raw value'
else:
name = 'value'
name = 'raw value' if raw else 'value'
for index, value in enumerate(values, 1):
lines.append('- %s %s: %s' % (name, index, value))

Expand Down Expand Up @@ -487,15 +475,9 @@ def format_result_value(bench):
loops = None
warmups = None
for run in bench._runs:
if run._is_calibration_warmups():
warmups = run._get_calibration_warmups()
elif run._is_recalibration_warmups():
if run._is_calibration_warmups() or run._is_recalibration_warmups():
warmups = run._get_calibration_warmups()
elif run._is_recalibration_loops():
loops = run._get_calibration_loops()
elif run._is_calibration_warmups():
loops = run._get_calibration_loops()
elif run._is_calibration_loops():
elif run._is_recalibration_loops() or run._is_calibration_warmups() or run._is_calibration_loops():
loops = run._get_calibration_loops()
else:
loops = None
Expand All @@ -517,15 +499,9 @@ def format_result(bench):
loops = None
warmups = None
for run in bench._runs:
if run._is_calibration_warmups():
warmups = run._get_calibration_warmups()
elif run._is_recalibration_warmups():
if run._is_calibration_warmups() or run._is_recalibration_warmups():
warmups = run._get_calibration_warmups()
elif run._is_recalibration_loops():
loops = run._get_calibration_loops()
elif run._is_calibration_warmups():
loops = run._get_calibration_loops()
elif run._is_calibration_loops():
elif run._is_recalibration_loops() or run._is_calibration_warmups() or run._is_calibration_loops():
loops = run._get_calibration_loops()
else:
loops = None
Expand Down Expand Up @@ -589,10 +565,7 @@ def multiline_output(args):

@contextlib.contextmanager
def catch_broken_pipe_error(file=None):
if file is None:
files = [sys.stdout, sys.stderr]
else:
files = [file]
files = [sys.stdout, sys.stderr] if file is None else [file]

try:
for file in files:
Expand All @@ -604,7 +577,7 @@ def catch_broken_pipe_error(file=None):
# was closed by the consumer
for file in files:
file.flush()
except IOError as exc:
except OSError as exc:
if exc.errno != errno.EPIPE:
raise
# got a broken pipe error: ignore it
Expand All @@ -613,7 +586,5 @@ def catch_broken_pipe_error(file=None):
# close at exit which would log the error:
# "Exception ignored in: ... BrokenPipeError: ..."
for file in files:
try:
with contextlib.suppress(OSError):
file.close()
except IOError:
pass
9 changes: 3 additions & 6 deletions pyperf/_collect_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ def collect_python_metadata(metadata):
# 'bbd45126bc691f669c4ebdfbd74456cd274c6b92'
# in 'Python 2.7.10 (bbd45126bc691f669c4ebdfbd74456cd274c6b92,'
match = re.search(r'^[^(]+\(([a-f0-9]{6,}\+?),', sys.version)
if match:
revision = match.group(1)
else:
revision = None
revision = match.group(1) if match else None
if revision:
version = '%s revision %s' % (version, revision)
metadata['python_version'] = version
Expand Down Expand Up @@ -136,7 +133,7 @@ def read_proc(path):
with open_text(path) as fp:
for line in fp:
yield line.rstrip()
except (OSError, IOError):
except OSError:
return


Expand Down Expand Up @@ -332,7 +329,7 @@ def get_cpu_temperature(path, cpu_temp):

try:
temp_label = read_first_line(template % 'label', error=True)
except IOError:
except OSError:
break

temp_input = read_first_line(template % 'input', error=True)
Expand Down
2 changes: 1 addition & 1 deletion pyperf/_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def get_tags_for_result(result):
return result.ref.benchmark.get_metadata().get("tags", [])


class CompareResult(object):
class CompareResult:
def __init__(self, ref, changed, min_speed=None):
# CompareData object
self.ref = ref
Expand Down
5 changes: 2 additions & 3 deletions pyperf/_cpu_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import re

from pyperf._utils import sysfs_path, proc_path, read_first_line, USE_PSUTIL
import contextlib

try:
if not USE_PSUTIL:
Expand All @@ -27,10 +28,8 @@ def get_logical_cpu_count():
except ImportError:
pass
else:
try:
with contextlib.suppress(NotImplementedError):
cpu_count = multiprocessing.cpu_count()
except NotImplementedError:
pass

if cpu_count is not None and cpu_count < 1:
return None
Expand Down
5 changes: 2 additions & 3 deletions pyperf/_linux_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
# Need Linux 2.6.16 or newer.
def read_smap_file():
total = 0
fp = open(proc_path("self/smaps"), "rb")
with fp:
with open(proc_path("self/smaps"), "rb") as fp:
for line in fp:
# Include both Private_Clean and Private_Dirty sections.
line = line.rstrip()
Expand Down Expand Up @@ -54,7 +53,7 @@ def check_tracking_memory():
mem_thread = PeakMemoryUsageThread()
try:
mem_thread.get()
except IOError as exc:
except OSError as exc:
path = proc_path("self/smaps")
return "unable to read %s: %s" % (path, exc)

Expand Down
2 changes: 1 addition & 1 deletion pyperf/_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
MAX_CALIBRATION = 5


class Manager(object):
class Manager:
"""
Manager process which spawns worker processes to:
- calibrate warmups
Expand Down
2 changes: 1 addition & 1 deletion pyperf/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def format_metadata(name, value):
return info.formatter(value)


class Metadata(object):
class Metadata:
def __init__(self, name, value):
self._name = name
self._value = value
Expand Down
Loading

0 comments on commit 373541d

Please sign in to comment.