Skip to content

Commit 0360c3c

Browse files
committed
Reformat all utility files
1 parent 30bd7d2 commit 0360c3c

File tree

7 files changed

+88
-65
lines changed

7 files changed

+88
-65
lines changed

pybm/util/common.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import re
22
from typing import List, Iterable, Tuple, Callable, TypeVar, Dict
33

4-
T = TypeVar('T')
5-
S = TypeVar('S')
6-
U = TypeVar('U')
7-
V = TypeVar('V')
4+
T = TypeVar("T")
5+
S = TypeVar("S")
6+
U = TypeVar("U")
7+
V = TypeVar("V")
88

99

1010
def lmap(fn: Callable[[S], T], iterable: Iterable[S]) -> List[T]:
@@ -23,17 +23,19 @@ def tfilter(fn: Callable[[S], bool], iterable: Iterable[S]) -> Tuple[S, ...]:
2323
return tuple(filter(fn, iterable))
2424

2525

26-
def lpartition(fn: Callable[[S], bool], iterable: Iterable[S]) -> \
27-
Tuple[List[S], List[S]]:
26+
def lpartition(
27+
fn: Callable[[S], bool], iterable: Iterable[S]
28+
) -> Tuple[List[S], List[S]]:
2829
"""Partition list into two with a boolean function. Not particularly
2930
efficient because of the double pass, but fine for small lists."""
3031
true_list = lfilter(lambda x: fn(x), iterable)
3132
false_list = lfilter(lambda x: not fn(x), iterable)
3233
return true_list, false_list
3334

3435

35-
def tpartition(fn: Callable[[S], bool], iterable: Iterable[S]) -> \
36-
Tuple[Tuple[S, ...], Tuple[S, ...]]:
36+
def tpartition(
37+
fn: Callable[[S], bool], iterable: Iterable[S]
38+
) -> Tuple[Tuple[S, ...], Tuple[S, ...]]:
3739
"""Partition tuple into two with a boolean function. Not particularly
3840
efficient because of the double pass, but fine for small tuples."""
3941
true_list = tfilter(lambda x: fn(x), iterable)
@@ -49,17 +51,15 @@ def dvmap(fn: Callable[[U], T], dictionary: Dict[S, U]) -> Dict[S, T]:
4951
return {k: fn(v) for k, v in dictionary.items()}
5052

5153

52-
def dmap(fn: Callable[[S, T], Tuple[U, V]], dictionary: Dict[S, T]) \
53-
-> Dict[U, V]:
54+
def dmap(fn: Callable[[S, T], Tuple[U, V]], dictionary: Dict[S, T]) -> Dict[U, V]:
5455
return {k: v for k, v in map(fn, dictionary.keys(), dictionary.values())}
5556

5657

5758
def dkfilter(fn: Callable[[S], bool], dictionary: Dict[S, T]) -> Dict[S, T]:
5859
return {k: dictionary[k] for k in lfilter(fn, dictionary.keys())}
5960

6061

61-
def dfilter(fn: Callable[[Tuple[S, T]], bool], dictionary: Dict[S, T]) \
62-
-> Dict[S, T]:
62+
def dfilter(fn: Callable[[Tuple[S, T]], bool], dictionary: Dict[S, T]) -> Dict[S, T]:
6363
return {k: v for k, v in tfilter(fn, dictionary.items())}
6464

6565

@@ -89,12 +89,12 @@ def flatten(t):
8989
return [item for sublist in t for item in sublist]
9090

9191

92-
def partition_n(n: int, fn: Callable[[T], int], listlike: Iterable[T]) \
93-
-> List[List[T]]:
92+
def partition_n(n: int, fn: Callable[[T], int], listlike: Iterable[T]) -> List[List[T]]:
9493
return_obj: List[List[T]] = [[] for _ in range(n)]
9594
for elem in listlike:
9695
k = fn(elem)
97-
assert 0 <= k < n, "partition function needs to return an integer " \
98-
"in the interval [0, {n})."
96+
assert (
97+
0 <= k < n
98+
), f"partition function needs to return an integer in the interval [0, {n})."
9999
return_obj[k].append(elem)
100100
return return_obj

pybm/util/extras.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
def get_extras():
22
"""Extra pybm functionality, specified as a valid argument to
33
setuptools.setup's 'extras_require' keyword argument."""
4-
extra_features = {
5-
"gbm": ["google-benchmark==0.2.0"]
6-
}
4+
extra_features = {"gbm": ["git+https://github.com/google/benchmark"]}
75
extra_features["all"] = sum(extra_features.values(), start=[])
86
return extra_features

pybm/util/git.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
def get_git_version() -> Tuple[int, ...]:
1414
rc, output = git_subprocess(["git", "--version"])
15-
version_str = re.search(r'([\d.]+)', output)
15+
version_str = re.search(r"([\d.]+)", output)
1616
if version_str is not None:
1717
version = version_str.group()
1818
return version_tuple(version)
@@ -30,19 +30,22 @@ def get_git_version() -> Tuple[int, ...]:
3030

3131
# ---------------------------------------
3232

33+
3334
def _feature_guard(min_git: Tuple[int, int, int]):
3435
if GIT_VERSION < min_git:
3536
min_git_str = version_string(min_git)
36-
msg = f"Command `git restore` requires at minimum git version " \
37-
f"{min_git_str}, "
37+
msg = f"Command `git restore` requires at minimum git version {min_git_str}, "
3838

3939
if GIT_VERSION == (0, 0, 0):
40-
msg += "but no git installation was found on your system. " \
41-
"Please assure that git is installed and added to PATH."
40+
msg += (
41+
"but no git installation was found on your system. "
42+
"Please assure that git is installed and added to PATH."
43+
)
4244
else:
4345
curr_git_str = version_string(GIT_VERSION)
44-
msg += f"but your installed git was found to be only version " \
45-
f"{curr_git_str}."
46+
msg += (
47+
f"but your installed git was found to be only version {curr_git_str}."
48+
)
4649
raise GitError(msg)
4750

4851

@@ -80,8 +83,10 @@ def resolve_ref(commit_ish: str, resolve_commits: bool):
8083
elif is_valid_sha1_part(commit_ish):
8184
ref_type = "commit"
8285
else:
83-
msg = f"Input {commit_ish!r} did not resolve to any known local " \
84-
f"branch, tag or valid commit SHA1."
86+
msg = (
87+
f"Input {commit_ish!r} did not resolve to any known local "
88+
f"branch, tag or valid commit SHA1."
89+
)
8590
raise GitError(msg)
8691
# force commit resolution, leads to detached HEAD
8792
if resolve_commits:
@@ -105,10 +110,10 @@ def process_line(line: str) -> Tuple[str, str]:
105110

106111
tag_marker = "^{}"
107112
# show-ref exits with 1 if no tags exist in the repo
108-
rc, tags = git_subprocess(["git", "show-ref", "--tags", "-d"],
109-
allowed_statuscodes=[1])
110-
commits_and_tags = lfilter(lambda x: x.endswith(tag_marker),
111-
tags.splitlines())
113+
rc, tags = git_subprocess(
114+
["git", "show-ref", "--tags", "-d"], allowed_statuscodes=[1]
115+
)
116+
commits_and_tags = lfilter(lambda x: x.endswith(tag_marker), tags.splitlines())
112117
# closure above is required here to keep mypy happy
113118
split_list = lmap(process_line, commits_and_tags)
114119
return dict(split_list)
@@ -151,8 +156,7 @@ def checkout(ref: str, cwd: Union[str, Path]):
151156
git_subprocess(command=command, cwd=cwd)
152157

153158

154-
def get_from_history(ref: str, resource: Union[str, Path],
155-
directory: Union[str, Path]):
159+
def get_from_history(ref: str, resource: Union[str, Path], directory: Union[str, Path]):
156160
"""Check out a file or directory from another git reference."""
157161
# Source:
158162
# https://stackoverflow.com/questions/307579/how-do-i-copy-a-version-of-a-single-file-from-one-git-branch-to-another

pybm/util/imports.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ def import_module_from_source(source_path: Union[str, Path]) -> ModuleType:
3535
# return loaded module
3636
return sys.modules[py_name]
3737
spec: Optional[ModuleSpec] = importlib.util.spec_from_file_location(
38-
py_name, source_path)
38+
py_name, source_path
39+
)
3940
if spec is not None:
4041
module = importlib.util.module_from_spec(spec)
4142
assert isinstance(spec.loader, Loader)
@@ -53,8 +54,9 @@ def import_func_from_source(source_path: str, fn_name: str) -> Callable:
5354
module = import_module_from_source(source_path)
5455
return getattr(module, fn_name)
5556
except (AttributeError, PybmError) as e:
56-
raise PybmError(f"Failed to import function {fn_name} from source "
57-
f"file {source_path}.") from e
57+
raise PybmError(
58+
f"Failed to import function {fn_name} from source " f"file {source_path}."
59+
) from e
5860

5961

6062
def import_from_module(identifier: str) -> Callable:
@@ -63,8 +65,10 @@ def import_from_module(identifier: str) -> Callable:
6365
*module_parts, name = identifier.split(".")
6466
module_name = ".".join(module_parts)
6567
if not module_exists(module_name):
66-
raise PybmError(f"Module {module_name} does not exist in the current "
67-
f"Python environment.")
68+
raise PybmError(
69+
f"Module {module_name} does not exist in the current "
70+
f"Python environment."
71+
)
6872
module = importlib.import_module(module_name)
6973
if not hasattr(module, name):
7074
raise PybmError(f"Module {module_name} has no member {name}.")
@@ -79,8 +83,7 @@ def import_function(name: str):
7983
pass
8084
try:
8185
source_path, fn_name = name.split(":")
82-
func = import_func_from_source(source_path=source_path,
83-
fn_name=fn_name)
86+
func = import_func_from_source(source_path=source_path, fn_name=fn_name)
8487
except (PybmError, AttributeError):
8588
pass
8689
return func

pybm/util/path.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from pathlib import Path
2-
from typing import Union, List
2+
from typing import Union, List, Optional
33

44
from pybm.util.common import lmap
55

@@ -14,11 +14,23 @@ def get_subdirs(path: Union[str, Path]):
1414
return [f.stem for f in filter(Path.is_dir, p.iterdir())]
1515

1616

17-
def list_contents(path: Union[str, Path], file_suffix: str = "",
18-
names_only: bool = True) -> List[str]:
19-
p = Path(path).resolve()
17+
def list_contents(
18+
path: Union[str, Path],
19+
file_suffix: str = "",
20+
rel_path: Optional[str] = None,
21+
names_only: bool = False,
22+
) -> List[str]:
23+
24+
resolved_path = Path(path).resolve()
25+
2026
glob_pattern = "*" if file_suffix == "" else "*" + file_suffix
27+
matching_files = resolved_path.glob(glob_pattern)
28+
2129
if names_only:
22-
return lmap(lambda x: str(x.name), p.glob(glob_pattern))
30+
return lmap(lambda x: x.name, matching_files)
31+
elif rel_path is not None:
32+
return lmap(
33+
lambda p: str(p.relative_to(rel_path)), matching_files # type: ignore
34+
)
2335
else:
24-
return lmap(str, p.glob(glob_pattern))
36+
return lmap(str, matching_files)

pybm/util/print.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,12 @@ def calculate_column_widths(data: Iterable[Iterable[str]]) -> List[int]:
1818
return lmap(max, data_lengths)
1919

2020

21-
def make_line(values: Iterable[str], column_widths: Iterable[int],
22-
padding: int) -> str:
21+
def make_line(values: Iterable[str], column_widths: Iterable[int], padding: int) -> str:
2322
pad_char = " " * padding
2423
sep = "|".join([pad_char] * 2)
2524
offset = pad_char
2625

27-
line = offset + sep.join(
28-
f"{n:<{w}}" for n, w in zip(values, column_widths)
29-
)
26+
line = offset + sep.join(f"{n:<{w}}" for n, w in zip(values, column_widths))
3027
return line
3128

3229

pybm/util/subprocess.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,36 @@
77
Handling = Literal["raise", "ignore"]
88

99

10-
def run_subprocess(command: List[str],
11-
allowed_statuscodes: List[int] = None,
12-
ex_type: type = PybmError,
13-
errors: Handling = "raise",
14-
cwd: Union[str, Path] = None) -> Tuple[int, str]:
10+
def run_subprocess(
11+
command: List[str],
12+
allowed_statuscodes: List[int] = None,
13+
ex_type: type = PybmError,
14+
errors: Handling = "raise",
15+
cwd: Union[str, Path] = None,
16+
) -> Tuple[int, str]:
1517
full_command = " ".join(command)
18+
1619
allowed_statuscodes = allowed_statuscodes or []
1720
allowed_statuscodes.append(0)
1821
# logger.debug(f"Running command {full_command}...")
19-
p = subprocess.run(command,
20-
stdout=subprocess.PIPE,
21-
stderr=subprocess.PIPE,
22-
encoding="utf-8",
23-
cwd=cwd)
22+
p = subprocess.run(
23+
command,
24+
stdout=subprocess.PIPE,
25+
stderr=subprocess.PIPE,
26+
encoding="utf-8",
27+
cwd=cwd,
28+
)
29+
2430
rc = p.returncode
2531
if rc not in allowed_statuscodes:
2632
if errors == "raise":
27-
msg = f"The command `{full_command}` returned the non-zero " \
28-
f"exit code {rc}.\nFurther information (stderr " \
29-
f"output of the subprocess):\n{p.stderr}"
33+
msg = (
34+
f"The command `{full_command}` returned the non-zero "
35+
f"exit code {rc}.\nFurther information (stderr "
36+
f"output of the subprocess):\n{p.stderr}"
37+
)
3038
raise ex_type(msg)
3139
else:
3240
return rc, p.stderr
41+
3342
return rc, p.stdout

0 commit comments

Comments
 (0)