Skip to content

Commit 8f0ffae

Browse files
committed
make ruff happy
1 parent 731248b commit 8f0ffae

File tree

24 files changed

+82
-301
lines changed

24 files changed

+82
-301
lines changed

docs/source/_exts/build_custom_js.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@
88

99

1010
def setup(app: Sphinx) -> None:
11-
subprocess.run("npm install", cwd=CUSTOM_JS_DIR, shell=True)
12-
subprocess.run("npm run build", cwd=CUSTOM_JS_DIR, shell=True)
11+
subprocess.run("npm install", cwd=CUSTOM_JS_DIR, shell=True) # noqa S607
12+
subprocess.run("npm run build", cwd=CUSTOM_JS_DIR, shell=True) # noqa S607

docs/source/guides/managing-state/sharing-component-state/_examples/filterable_list/main.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,8 @@ def Table(value, set_value):
3434
tr = html.tr(name, descr, value)
3535
if not value:
3636
rows.append(tr)
37-
else:
38-
if value.lower() in row["name"].lower():
39-
rows.append(tr)
37+
elif value.lower() in row["name"].lower():
38+
rows.append(tr)
4039
headers = html.tr(html.td(html.b("name")), html.td(html.b("description")))
4140
table = html.table(html.thead(headers), html.tbody(rows))
4241
return table

docs/source/reference/_examples/pigeon_maps.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def MapWithMarkers():
1212
Marker(
1313
{
1414
"anchor": anchor,
15-
"onClick": lambda: remove_marker_anchor(anchor),
15+
"onClick": lambda event, a=anchor: remove_marker_anchor(a),
1616
},
1717
key=str(anchor),
1818
)

pyproject.toml

+11-2
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ select = [
3939
"C",
4040
"DTZ",
4141
"E",
42-
"EM",
42+
# error message linting is overkill
43+
# "EM",
4344
"F",
4445
# TODO: turn this on later
4546
# "FBT",
@@ -63,14 +64,22 @@ select = [
6364
ignore = [
6465
# TODO: turn this on later
6566
"N802", "N806", # allow TitleCase functions/variables
67+
# We're not any cryptography
68+
"S311",
69+
# For loop variable re-assignment seems like an uncommon mistake
70+
"PLW2901",
6671
# Let Black deal with line-length
6772
"E501",
73+
# Allow args/attrs to shadow built-ins
74+
"A002", "A003",
6875
# Allow unused args (useful for documenting what the parameter is for later)
69-
"ARG001", "ARG005",
76+
"ARG001", "ARG002", "ARG005",
7077
# Allow non-abstract empty methods in abstract base classes
7178
"B027",
7279
# Allow boolean positional values in function calls, like `dict.get(... True)`
7380
"FBT003",
81+
# If we're making an explicit comparison to a falsy value it was probably intentional
82+
"PLC1901",
7483
# Ignore checks for possible passwords
7584
"S105", "S106", "S107",
7685
# Ignore complexity

scripts/live_docs.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ def main():
8686
ignore_handler = _get_ignore_handler(args)
8787
server.watch(srcdir, builder, ignore=ignore_handler)
8888
for dirpath in args.additional_watched_dirs:
89-
dirpath = os.path.realpath(dirpath)
90-
server.watch(dirpath, builder, ignore=ignore_handler)
89+
real_dirpath = os.path.realpath(dirpath)
90+
server.watch(real_dirpath, builder, ignore=ignore_handler)
9191
server.watch(outdir, ignore=ignore_handler)
9292

9393
if not args.no_initial_build:

scripts/run_docs.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55
# to import docs
66
sys.path.insert(0, os.getcwd())
77

8-
from docs.app import make_app
8+
from docs.app import make_app # noqa: E402
99

1010
app = make_app()
1111

1212
if __name__ == "__main__":
1313
app.run(
14-
host="0.0.0.0",
14+
host="0.0.0.0", # noqa: S104
1515
port=int(os.environ.get("PORT", 5000)),
1616
workers=int(os.environ.get("WEB_CONCURRENCY", 1)),
1717
debug=bool(int(os.environ.get("DEBUG", "0"))),

src/py/reactpy/reactpy/_console/ast_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def find_element_constructor_usages(
129129
node.args.insert(1, maybe_attr_dict_node)
130130
else:
131131
continue
132-
elif len(node.args) >= 2:
132+
elif len(node.args) >= 2: # noqa: PLR2004
133133
maybe_attr_dict_node = node.args[1]
134134
elif hasattr(html, name):
135135
if len(node.args) == 0:

src/py/reactpy/reactpy/_warnings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def warn(*args: Any, **kwargs: Any) -> Any:
1313

1414

1515
if TYPE_CHECKING:
16-
warn = _warn
16+
warn = _warn # noqa F811
1717

1818

1919
def _frame_depth_in_module() -> int:

src/py/reactpy/reactpy/backend/default.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ async def serve_development_app(
5050

5151
def _default_implementation() -> BackendImplementation[Any]:
5252
"""Get the first available server implementation"""
53-
global _DEFAULT_IMPLEMENTATION
53+
global _DEFAULT_IMPLEMENTATION # noqa PLW0603
5454

5555
if _DEFAULT_IMPLEMENTATION is not None:
5656
return _DEFAULT_IMPLEMENTATION
@@ -60,7 +60,7 @@ def _default_implementation() -> BackendImplementation[Any]:
6060
except StopIteration: # pragma: no cover
6161
logger.debug("Backend implementation import failed", exc_info=exc_info())
6262
msg = "No built-in server implementation installed."
63-
raise RuntimeError(msg)
63+
raise RuntimeError(msg) from None
6464
else:
6565
_DEFAULT_IMPLEMENTATION = implementation
6666
return implementation

src/py/reactpy/reactpy/backend/flask.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,9 @@ async def main() -> None:
256256

257257
dispatch_thread_info_created.wait()
258258
dispatch_thread_info = cast(_DispatcherThreadInfo, dispatch_thread_info_ref.current)
259-
assert dispatch_thread_info is not None
259+
260+
if dispatch_thread_info is None:
261+
raise RuntimeError("Failed to create dispatcher thread")
260262

261263
stop = ThreadEvent()
262264

src/py/reactpy/reactpy/core/_f_back.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ def f_module_name(index: int = 0) -> str:
99
if frame is None:
1010
return "" # pragma: no cover
1111
name = frame.f_globals.get("__name__", "")
12-
assert isinstance(name, str), "Expected module name to be a string"
12+
if not isinstance(name, str):
13+
raise TypeError("Expected module name to be a string")
1314
return name
1415

1516

src/py/reactpy/reactpy/core/hooks.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -246,13 +246,13 @@ def use_context(context: Context[_Type]) -> _Type:
246246
provider = hook.get_context_provider(context)
247247

248248
if provider is None:
249-
# force type checker to realize this is just a normal function
250-
assert isinstance(context, FunctionType), f"{context} is not a Context"
251-
# __kwdefault__ can be None if no kwarg only parameters exist
252-
assert context.__kwdefaults__ is not None, f"{context} has no 'value' kwarg"
253-
# lastly check that 'value' kwarg exists
254-
assert "value" in context.__kwdefaults__, f"{context} has no 'value' kwarg"
255-
# then we can safely access the context's default value
249+
# same assertions but with normal exceptions
250+
if not isinstance(context, FunctionType):
251+
raise TypeError(f"{context} is not a Context")
252+
if context.__kwdefaults__ is None:
253+
raise TypeError(f"{context} has no 'value' kwarg")
254+
if "value" not in context.__kwdefaults__:
255+
raise TypeError(f"{context} has no 'value' kwarg")
256256
return cast(_Type, context.__kwdefaults__["value"])
257257

258258
return provider._value
@@ -455,7 +455,7 @@ class _Memo(Generic[_Type]):
455455

456456
def empty(self) -> bool:
457457
try:
458-
self.value
458+
self.value # noqa: B018
459459
except AttributeError:
460460
return True
461461
else:
@@ -708,8 +708,8 @@ def set_current(self) -> None:
708708

709709
def unset_current(self) -> None:
710710
"""Unset this hook as the active hook in this thread"""
711-
# this assertion should never fail - primarilly useful for debug
712-
assert _hook_stack.get().pop() is self
711+
if _hook_stack.get().pop() is not self:
712+
raise RuntimeError("Hook stack is in an invalid state")
713713

714714
def _schedule_render(self) -> None:
715715
try:

src/py/reactpy/reactpy/core/layout.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -318,21 +318,20 @@ def _render_model_children(
318318
index,
319319
key,
320320
)
321+
elif old_child_state.is_component_state:
322+
self._unmount_model_states([old_child_state])
323+
new_child_state = _make_element_model_state(
324+
new_state,
325+
index,
326+
key,
327+
)
328+
old_child_state = None
321329
else:
322-
if old_child_state.is_component_state:
323-
self._unmount_model_states([old_child_state])
324-
new_child_state = _make_element_model_state(
325-
new_state,
326-
index,
327-
key,
328-
)
329-
old_child_state = None
330-
else:
331-
new_child_state = _update_element_model_state(
332-
old_child_state,
333-
new_state,
334-
index,
335-
)
330+
new_child_state = _update_element_model_state(
331+
old_child_state,
332+
new_state,
333+
index,
334+
)
336335
self._render_model(exit_stack, old_child_state, new_child_state, child)
337336
new_state.append_child(new_child_state.model.current)
338337
new_state.children_by_key[key] = new_child_state
@@ -595,7 +594,8 @@ def is_component_state(self) -> bool:
595594
@property
596595
def parent(self) -> _ModelState:
597596
parent = self._parent_ref()
598-
assert parent is not None, "detached model state"
597+
if parent is None:
598+
raise RuntimeError("detached model state")
599599
return parent
600600

601601
def append_child(self, child: Any) -> None:

src/py/reactpy/reactpy/core/serve.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from __future__ import annotations
22

3-
from asyncio import create_task
43
from collections.abc import Awaitable
54
from logging import getLogger
65
from typing import Callable
76

87
from anyio import create_task_group
8+
from anyio.abc import TaskGroup
99

1010
from reactpy.core.types import LayoutEventMessage, LayoutType, LayoutUpdateMessage
1111

@@ -40,7 +40,7 @@ async def serve_layout(
4040
try:
4141
async with create_task_group() as task_group:
4242
task_group.start_soon(_single_outgoing_loop, layout, send)
43-
task_group.start_soon(_single_incoming_loop, layout, recv)
43+
task_group.start_soon(_single_incoming_loop, task_group, layout, recv)
4444
except Stop:
4545
logger.info(f"Stopped serving {layout}")
4646

@@ -53,9 +53,11 @@ async def _single_outgoing_loop(
5353

5454

5555
async def _single_incoming_loop(
56-
layout: LayoutType[LayoutUpdateMessage, LayoutEventMessage], recv: RecvCoroutine
56+
task_group: TaskGroup,
57+
layout: LayoutType[LayoutUpdateMessage, LayoutEventMessage],
58+
recv: RecvCoroutine,
5759
) -> None:
5860
while True:
5961
# We need to fire and forget here so that we avoid waiting on the completion
6062
# of this event handler before receiving and running the next one.
61-
create_task(layout.deliver(await recv()))
63+
task_group.start_soon(layout.deliver, await recv())

src/py/reactpy/reactpy/testing/common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ def capture(self, render_function: Callable[..., Any]) -> Callable[..., Any]:
141141
@wraps(render_function)
142142
def wrapper(*args: Any, **kwargs: Any) -> Any:
143143
self = self_ref()
144-
assert self is not None, "Hook catcher has been garbage collected"
144+
if self is None:
145+
raise RuntimeError("Hook catcher has been garbage collected")
145146

146147
hook = current_hook()
147148
if self.index_by_kwarg is not None:

src/py/reactpy/reactpy/utils.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ def _mutate_vdom(vdom: VdomDict) -> None:
214214
and isinstance(vdom["attributes"]["style"], str)
215215
):
216216
# Convince type checker that it's safe to mutate attributes
217-
assert isinstance(vdom["attributes"], dict)
217+
assert isinstance(vdom["attributes"], dict) # noqa: S101
218218

219219
# Convert style attribute from str -> dict with camelCase keys
220220
vdom["attributes"]["style"] = {
@@ -291,9 +291,8 @@ def _vdom_attr_to_html_str(key: str, value: Any) -> tuple[str, str]:
291291
):
292292
key = _CAMEL_CASE_SUB_PATTERN.sub("-", key)
293293

294-
assert not callable(
295-
value
296-
), f"Could not convert callable attribute {key}={value} to HTML"
294+
if callable(value):
295+
raise TypeError(f"Cannot convert callable attribute {key}={value} to HTML")
297296

298297
# Again, we lower the attribute name only to normalize - HTML is case-insensitive:
299298
# http://w3c.github.io/html-reference/documents.html#case-insensitivity

src/py/reactpy/reactpy/web/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def resolve_module_exports_from_url(
5656
return set()
5757

5858
try:
59-
text = requests.get(url).text
59+
text = requests.get(url, timeout=5).text
6060
except requests.exceptions.ConnectionError as error:
6161
reason = "" if error is None else " - {error.errno}"
6262
logger.warning("Did not resolve exports for url " + url + reason)

0 commit comments

Comments
 (0)