Skip to content
Merged

Furb #326

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
1,132 changes: 113 additions & 1,019 deletions .basedpyright/baseline.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ extend-select = [
"TC", # flake8-type-checking
"UP", # pyupgrade
"W", # pycodestyle
"FURB",
]
extend-ignore = [
"C90", # McCabe complexity
Expand Down
25 changes: 11 additions & 14 deletions pytools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
Sequence,
)
from functools import reduce, wraps
from pathlib import Path
from sys import intern
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -2144,28 +2145,25 @@ def objname(obj: Any) -> str:
return objname(val)


def invoke_editor(s, filename="edit.txt", descr="the file"):
def invoke_editor(s: str, filename: str = "edit.txt", descr: str = "the file"):
from tempfile import mkdtemp
tempdir = mkdtemp()
tempdir = Path(mkdtemp())

from os.path import join
full_name = join(tempdir, filename)
full_path = tempdir / filename

with open(full_name, "w") as outf:
outf.write(str(s))
full_path.write_text(str(s))

import os
if "EDITOR" in os.environ:
from subprocess import Popen
p = Popen([os.environ["EDITOR"], full_name])
p = Popen([os.environ["EDITOR"], full_path])
os.waitpid(p.pid, 0)
else:
print("(Set the EDITOR environment variable to be "
"dropped directly into an editor next time.)")
input(f"Edit {descr} at {full_name} now, then hit [Enter]:")
input(f"Edit {descr} at {full_path} now, then hit [Enter]:")

with open(full_name) as inf:
result = inf.read()
result = full_path.read_text()

return result

Expand Down Expand Up @@ -2514,8 +2512,7 @@ def download_from_web_if_not_present(url: str, local_name: str | None = None) ->
with urlopen(req) as inf:
contents = inf.read()

with open(local_name, "wb") as outf:
outf.write(contents)
Path(local_name).write_bytes(contents)

# }}}

Expand Down Expand Up @@ -2861,7 +2858,7 @@ def natorder(item: str) -> list[int]:
result: list[int] = []
for (int_val, string_val) in re.findall(r"(\d+)|(\D+)", item):
if int_val:
result.append(int(int_val))
result.append(int(int_val)) # noqa: FURB113
# Tie-breaker in case of leading zeros in *int_val*. Longer values
# compare smaller to preserve order of numbers in decimal notation,
# e.g., "1.001" < "1.01"
Expand Down Expand Up @@ -2912,7 +2909,7 @@ def identity(x: T) -> str:
# https://github.com/python/cpython/commit/1ed61617a4a6632905ad6a0b440cd2cafb8b6414

_DOTTED_WORDS = r"[a-z_]\w*(\.[a-z_]\w*)*"
_NAME_PATTERN = re.compile(f"^({_DOTTED_WORDS})(:({_DOTTED_WORDS})?)?$", re.I)
_NAME_PATTERN = re.compile(f"^({_DOTTED_WORDS})(:({_DOTTED_WORDS})?)?$", re.IGNORECASE)
del _DOTTED_WORDS


Expand Down
148 changes: 0 additions & 148 deletions pytools/batchjob.py

This file was deleted.

8 changes: 4 additions & 4 deletions pytools/convergence.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,14 @@ def __str__(self):

def write_gnuplot_file(self, filename: str) -> None:
with open(filename, "w") as outfile:
for absc, err in self.history:
outfile.write(f"{absc:f} {err:f}\n")
outfile.writelines(f"{absc:f} {err:f}\n" for absc, err in self.history)
result = self.estimate_order_of_convergence()
const = result[0, 0]
order = result[0, 1]
outfile.write("\n")
for absc, _err in self.history:
outfile.write(f"{absc:f} {const * absc**(-order):f}\n")
outfile.writelines(
f"{absc:f} {const * absc**(-order):f}\n"
for absc, _err in self.history)


def stringify_eocs(*eocs: EOCRecorder,
Expand Down
16 changes: 11 additions & 5 deletions pytools/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@

import contextlib
import sys
from collections import UserDict
from typing import TypeVar

from typing_extensions import override

from pytools import memoize


K = TypeVar("K")
V = TypeVar("V")


# {{{ debug files -------------------------------------------------------------

def make_unique_filesystem_object(stem, extension="", directory="",
Expand Down Expand Up @@ -171,22 +177,22 @@ def setup_readline():
setup_readline()


class SetPropagatingDict(dict):
class SetPropagatingDict(UserDict[K, V]):
def __init__(self, source_dicts, target_dict):
dict.__init__(self)
super().__init__()
for s in source_dicts[::-1]:
self.update(s)

self.target_dict = target_dict

@override
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
super().__setitem__(key, value)
self.target_dict[key] = value

@override
def __delitem__(self, key):
dict.__delitem__(self, key)
super().__delitem__(key)
del self.target_dict[key]


Expand All @@ -199,7 +205,7 @@ def shell(locals_=None, globals_=None):
if globals_ is None:
globals_ = calling_frame.f_globals

ns = SetPropagatingDict([locals_, globals_], locals_)
ns = SetPropagatingDict[str, object]([locals_, globals_], locals_)

if HAVE_READLINE:
readline.set_completer(
Expand Down
5 changes: 3 additions & 2 deletions pytools/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,9 @@ def compute_sccs(graph: GraphT[NodeT]) -> list[list[NodeT]]:
for child in children:
if child not in visit_order:
# Recurse.
call_stack.append((top, children, child))
call_stack.append((child, iter(graph[child]), None))
call_stack.extend((
(top, children, child),
(child, iter(graph[child]), None)))
break
if child in visiting:
scc_root[top] = min(
Expand Down
18 changes: 9 additions & 9 deletions pytools/graphviz.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import html
import logging
import os
from pathlib import Path


logger = logging.getLogger(__name__)
Expand All @@ -58,7 +59,7 @@ def dot_escape(s: str) -> str:
return html.escape(s.replace("\\", "\\\\"))


def show_dot(dot_code: str, output_to: str | None = None) -> str | None:
def show_dot(dot_code: str, output_to: str | None = None) -> Path | None:
"""
Visualize the graph represented by *dot_code*.

Expand All @@ -82,13 +83,11 @@ def show_dot(dot_code: str, output_to: str | None = None) -> str | None:

import subprocess
from tempfile import mkdtemp
temp_dir = mkdtemp(prefix="tmp_pytools_dot")
temp_path = Path(mkdtemp(prefix="tmp_pytools_dot"))

dot_file_name = "code.dot"

from os.path import join
with open(join(temp_dir, dot_file_name), "w") as dotf:
dotf.write(dot_code)
(temp_path / dot_file_name).write_text(dot_code)

# {{{ preprocess 'output_to'

Expand All @@ -110,26 +109,27 @@ def show_dot(dot_code: str, output_to: str | None = None) -> str | None:
# }}}

if output_to == "xwindow":
subprocess.check_call(["dot", "-Tx11", dot_file_name], cwd=temp_dir)
subprocess.check_call(["dot", "-Tx11", dot_file_name], cwd=temp_path)
elif output_to in ["browser", "svg"]:
svg_file_name = "code.svg"
subprocess.check_call(["dot", "-Tsvg", "-o", svg_file_name, dot_file_name],
cwd=temp_dir)
cwd=temp_path)

full_svg_file_name = join(temp_dir, svg_file_name)
full_svg_file_name = temp_path / svg_file_name
logger.info("show_dot: svg written to '%s'", full_svg_file_name)

if output_to == "svg":
return full_svg_file_name
assert output_to == "browser"

from webbrowser import open as browser_open
browser_open("file://" + full_svg_file_name)
browser_open(full_svg_file_name.as_uri())
else:
raise ValueError("`output_to` can be one of 'xwindow', 'browser', or 'svg',"
f" got '{output_to}'")

return None

# }}}


Expand Down
2 changes: 1 addition & 1 deletion pytools/py_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def __setstate__(self, obj: (
f"(got: {magic!r}, expected: {BYTECODE_VERSION!r})")

unique_filename = _linecache_unique_name(
name_prefix if name_prefix else "module", source_code)
name_prefix or "module", source_code)
mod_globals = _get_empty_module_dict(unique_filename)
mod_globals.update(nondefault_globals)

Expand Down
Loading
Loading