Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 46239ca

Browse filesBrowse files
authored
Re ruff (pyscript#2292)
* Ruff fixes * Ruff fixes * from __future__ import annotations breaks MicroPython * noqa: FURB188 because there is no str.replacesuffix() in MicroPython * Add ruff to pre-commit
1 parent 0366e48 commit 46239ca
Copy full SHA for 46239ca

File tree

Expand file treeCollapse file tree

20 files changed

+117
-100
lines changed
Filter options
Expand file treeCollapse file tree

20 files changed

+117
-100
lines changed

‎.pre-commit-config.yaml

Copy file name to clipboardExpand all lines: .pre-commit-config.yaml
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ repos:
3838
additional_dependencies:
3939
- tomli
4040

41+
- repo: https://github.com/astral-sh/ruff-pre-commit
42+
rev: v0.9.6
43+
hooks:
44+
- id: ruff
45+
4146
- repo: https://github.com/hoodmane/pyscript-prettier-precommit
4247
rev: "v3.0.0-alpha.6"
4348
hooks:

‎core/src/stdlib/pyscript/display.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/display.py
+9-8Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,14 @@ def _eval_formatter(obj, print_method):
7373
"""
7474
if print_method == "__repr__":
7575
return repr(obj)
76-
elif hasattr(obj, print_method):
76+
if hasattr(obj, print_method):
7777
if print_method == "savefig":
7878
buf = io.BytesIO()
7979
obj.savefig(buf, format="png")
8080
buf.seek(0)
8181
return base64.b64encode(buf.read()).decode("utf-8")
8282
return getattr(obj, print_method)()
83-
elif print_method == "_repr_mimebundle_":
83+
if print_method == "_repr_mimebundle_":
8484
return {}, {}
8585
return None
8686

@@ -107,7 +107,7 @@ def _format_mime(obj):
107107

108108
if output is None:
109109
continue
110-
elif mime_type not in _MIME_RENDERERS:
110+
if mime_type not in _MIME_RENDERERS:
111111
not_available.append(mime_type)
112112
continue
113113
break
@@ -149,9 +149,11 @@ def display(*values, target=None, append=True):
149149
if target is None:
150150
target = current_target()
151151
elif not isinstance(target, str):
152-
raise TypeError(f"target must be str or None, not {target.__class__.__name__}")
152+
msg = f"target must be str or None, not {target.__class__.__name__}"
153+
raise TypeError(msg)
153154
elif target == "":
154-
raise ValueError("Cannot have an empty target")
155+
msg = "Cannot have an empty target"
156+
raise ValueError(msg)
155157
elif target.startswith("#"):
156158
# note: here target is str and not None!
157159
# align with @when behavior
@@ -161,9 +163,8 @@ def display(*values, target=None, append=True):
161163

162164
# If target cannot be found on the page, a ValueError is raised
163165
if element is None:
164-
raise ValueError(
165-
f"Invalid selector with id={target}. Cannot be found in the page."
166-
)
166+
msg = f"Invalid selector with id={target}. Cannot be found in the page."
167+
raise ValueError(msg)
167168

168169
# if element is a <script type="py">, it has a 'target' attribute which
169170
# points to the visual element holding the displayed values. In that case,

‎core/src/stdlib/pyscript/events.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/events.py
+4-2Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ def add_listener(self, listener):
3636
if listener not in self._listeners:
3737
self._listeners.append(listener)
3838
else:
39-
raise ValueError("Listener must be callable or awaitable.")
39+
msg = "Listener must be callable or awaitable."
40+
raise ValueError(msg)
4041

4142
def remove_listener(self, *args):
4243
"""
@@ -76,7 +77,8 @@ def when(target, *args, **kwargs):
7677
# Extract the selector from the arguments or keyword arguments.
7778
selector = args[0] if args else kwargs.pop("selector")
7879
if not selector:
79-
raise ValueError("No selector provided.")
80+
msg = "No selector provided."
81+
raise ValueError(msg)
8082
# Grab the DOM elements to which the target event will be attached.
8183
from pyscript.web import Element, ElementCollection
8284

‎core/src/stdlib/pyscript/flatted.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/flatted.py
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def _object_keys(value):
3131

3232

3333
def _is_array(value):
34-
return isinstance(value, list) or isinstance(value, tuple)
34+
return isinstance(value, (list, tuple))
3535

3636

3737
def _is_object(value):
@@ -60,10 +60,10 @@ def _loop(keys, input, known, output):
6060

6161

6262
def _ref(key, value, input, known, output):
63-
if _is_array(value) and not value in known:
63+
if _is_array(value) and value not in known:
6464
known.append(value)
6565
value = _loop(_array_keys(value), input, known, value)
66-
elif _is_object(value) and not value in known:
66+
elif _is_object(value) and value not in known:
6767
known.append(value)
6868
value = _loop(_object_keys(value), input, known, value)
6969

‎core/src/stdlib/pyscript/magic_js.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/magic_js.py
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def __getattr__(self, field):
2525
# avoid pyodide looking for non existent fields
2626
if not field.startswith("_"):
2727
return getattr(getattr(js_modules, self.name), field)
28+
return None
2829

2930

3031
# generate N modules in the system that will proxy the real value

‎core/src/stdlib/pyscript/media.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/media.py
+1-2Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ async def load(cls, audio=False, video=True):
4444
for k in video:
4545
setattr(options.video, k, to_js(video[k]))
4646

47-
stream = await window.navigator.mediaDevices.getUserMedia(options)
48-
return stream
47+
return await window.navigator.mediaDevices.getUserMedia(options)
4948

5049
async def get_stream(self):
5150
key = self.kind.replace("input", "").replace("output", "")

‎core/src/stdlib/pyscript/storage.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/storage.py
+6-4Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@ def _to_idb(value):
1010
if isinstance(value, (bool, float, int, str, list, dict, tuple)):
1111
return _stringify(["generic", value])
1212
if isinstance(value, bytearray):
13-
return _stringify(["bytearray", [v for v in value]])
13+
return _stringify(["bytearray", list(value)])
1414
if isinstance(value, memoryview):
15-
return _stringify(["memoryview", [v for v in value]])
16-
raise TypeError(f"Unexpected value: {value}")
15+
return _stringify(["memoryview", list(value)])
16+
msg = f"Unexpected value: {value}"
17+
raise TypeError(msg)
1718

1819

1920
# convert an IndexedDB compatible entry into a Python value
@@ -56,5 +57,6 @@ async def sync(self):
5657

5758
async def storage(name="", storage_class=Storage):
5859
if not name:
59-
raise ValueError("The storage name must be defined")
60+
msg = "The storage name must be defined"
61+
raise ValueError(msg)
6062
return storage_class(await _storage(f"@pyscript/{name}"))

‎core/src/stdlib/pyscript/util.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/util.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def as_bytearray(buffer):
1111
ui8a = js.Uint8Array.new(buffer)
1212
size = ui8a.length
1313
ba = bytearray(size)
14-
for i in range(0, size):
14+
for i in range(size):
1515
ba[i] = ui8a[i]
1616
return ba
1717

‎core/src/stdlib/pyscript/web.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/web.py
+27-20Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
# `when` is not used in this module. It is imported here save the user an additional
44
# import (i.e. they can get what they need from `pyscript.web`).
5-
from pyscript import document, when, Event # NOQA
5+
6+
# from __future__ import annotations # CAUTION: This is not supported in MicroPython.
7+
8+
from pyscript import document, when, Event # noqa: F401
69
from pyscript.ffi import create_proxy
710

811

@@ -100,7 +103,7 @@ def __getitem__(self, key):
100103
If `key` is an integer or a slice we use it to index/slice the element's
101104
children. Otherwise, we use `key` as a query selector.
102105
"""
103-
if isinstance(key, int) or isinstance(key, slice):
106+
if isinstance(key, (int, slice)):
104107
return self.children[key]
105108

106109
return self.find(key)
@@ -120,7 +123,7 @@ def __getattr__(self, name):
120123
# attribute `for` which is a Python keyword, so you can access it on the
121124
# Element instance via `for_`).
122125
if name.endswith("_"):
123-
name = name[:-1]
126+
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
124127
return getattr(self._dom_element, name)
125128

126129
def __setattr__(self, name, value):
@@ -138,7 +141,7 @@ def __setattr__(self, name, value):
138141
# attribute `for` which is a Python keyword, so you can access it on the
139142
# Element instance via `for_`).
140143
if name.endswith("_"):
141-
name = name[:-1]
144+
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
142145

143146
if name.startswith("on_"):
144147
# Ensure on-events are cached in the _on_events dict if the
@@ -152,10 +155,12 @@ def get_event(self, name):
152155
Get an `Event` instance for the specified event name.
153156
"""
154157
if not name.startswith("on_"):
155-
raise ValueError("Event names must start with 'on_'.")
158+
msg = "Event names must start with 'on_'."
159+
raise ValueError(msg)
156160
event_name = name[3:] # Remove the "on_" prefix.
157161
if not hasattr(self._dom_element, event_name):
158-
raise ValueError(f"Element has no '{event_name}' event.")
162+
msg = f"Element has no '{event_name}' event."
163+
raise ValueError(msg)
159164
if name in self._on_events:
160165
return self._on_events[name]
161166
# Such an on-event exists in the DOM element, but we haven't yet
@@ -203,7 +208,7 @@ def append(self, *items):
203208
# We check for list/tuple here and NOT for any iterable as it will match
204209
# a JS Nodelist which is handled explicitly below.
205210
# NodeList.
206-
elif isinstance(item, list) or isinstance(item, tuple):
211+
elif isinstance(item, (list, tuple)):
207212
for child in item:
208213
self.append(child)
209214

@@ -227,10 +232,11 @@ def append(self, *items):
227232

228233
except AttributeError:
229234
# Nope! This is not an element or a NodeList.
230-
raise TypeError(
235+
msg = (
231236
f'Element "{item}" is a proxy object, "'
232237
f"but not a valid element or a NodeList."
233238
)
239+
raise TypeError(msg)
234240

235241
def clone(self, clone_id=None):
236242
"""Make a clone of the element (clones the underlying DOM object too)."""
@@ -401,9 +407,8 @@ def add(self, value=None, html=None, text=None, before=None, **kwargs):
401407

402408
new_option = option(**kwargs)
403409

404-
if before:
405-
if isinstance(before, Element):
406-
before = before._dom_element
410+
if before and isinstance(before, Element):
411+
before = before._dom_element
407412

408413
self._element._dom_element.add(new_option._dom_element, before)
409414

@@ -463,7 +468,7 @@ def __init__(
463468
)
464469

465470
for child in list(args) + (children or []):
466-
if isinstance(child, Element) or isinstance(child, ElementCollection):
471+
if isinstance(child, (Element, ElementCollection)):
467472
self.append(child)
468473

469474
else:
@@ -493,14 +498,13 @@ def __eq__(self, other):
493498
)
494499

495500
def __iter__(self):
496-
for class_name in self._all_class_names():
497-
yield class_name
501+
yield from self._all_class_names()
498502

499503
def __len__(self):
500504
return len(self._all_class_names())
501505

502506
def __repr__(self):
503-
return f"ClassesCollection({repr(self._collection)})"
507+
return f"ClassesCollection({self._collection!r})"
504508

505509
def __str__(self):
506510
return " ".join(self._all_class_names())
@@ -553,7 +557,7 @@ def __setitem__(self, key, value):
553557
element.style[key] = value
554558

555559
def __repr__(self):
556-
return f"StyleCollection({repr(self._collection)})"
560+
return f"StyleCollection({self._collection!r})"
557561

558562
def remove(self, key):
559563
"""Remove a CSS property from the elements in the collection."""
@@ -588,7 +592,7 @@ def __getitem__(self, key):
588592
if isinstance(key, int):
589593
return self._elements[key]
590594

591-
elif isinstance(key, slice):
595+
if isinstance(key, slice):
592596
return ElementCollection(self._elements[key])
593597

594598
return self.find(key)
@@ -1125,7 +1129,8 @@ def snap(
11251129

11261130
elif isinstance(to, Element):
11271131
if to.tag != "canvas":
1128-
raise TypeError("Element to snap to must be a canvas.")
1132+
msg = "Element to snap to must be a canvas."
1133+
raise TypeError(msg)
11291134

11301135
elif getattr(to, "tagName", "") == "CANVAS":
11311136
to = canvas(dom_element=to)
@@ -1134,10 +1139,12 @@ def snap(
11341139
elif isinstance(to, str):
11351140
nodelist = document.querySelectorAll(to) # NOQA
11361141
if nodelist.length == 0:
1137-
raise TypeError("No element with selector {to} to snap to.")
1142+
msg = "No element with selector {to} to snap to."
1143+
raise TypeError(msg)
11381144

11391145
if nodelist[0].tagName != "CANVAS":
1140-
raise TypeError("Element to snap to must be a canvas.")
1146+
msg = "Element to snap to must be a canvas."
1147+
raise TypeError(msg)
11411148

11421149
to = canvas(dom_element=nodelist[0])
11431150

‎core/src/stdlib/pyscript/websocket.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/websocket.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __getattr__(self, attr):
2424
return value
2525

2626

27-
class WebSocket(object):
27+
class WebSocket:
2828
CONNECTING = 0
2929
OPEN = 1
3030
CLOSING = 2

‎core/src/stdlib/pyscript/workers.py

Copy file name to clipboardExpand all lines: core/src/stdlib/pyscript/workers.py
+5-3Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@ async def create_named_worker(src="", name="", config=None, type="py"):
2525
from json import dumps
2626

2727
if not src:
28-
raise ValueError("Named workers require src")
28+
msg = "Named workers require src"
29+
raise ValueError(msg)
2930

3031
if not name:
31-
raise ValueError("Named workers require a name")
32+
msg = "Named workers require a name"
33+
raise ValueError(msg)
3234

3335
s = _js.document.createElement("script")
3436
s.type = type
@@ -37,7 +39,7 @@ async def create_named_worker(src="", name="", config=None, type="py"):
3739
_set(s, "name", name)
3840

3941
if config:
40-
_set(s, "config", isinstance(config, str) and config or dumps(config))
42+
_set(s, "config", (isinstance(config, str) and config) or dumps(config))
4143

4244
_js.document.body.append(s)
4345
return await workers[name]
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import numpy
2-
import matplotlib
1+
import numpy as np
2+
import matplotlib as mpl
33

44
# just do something with the packages
5-
print(len(dir(numpy)))
6-
print(len(dir(matplotlib)))
5+
print(len(dir(np)))
6+
print(len(dir(mpl)))

‎core/tests/javascript/workers/worker.py

Copy file name to clipboardExpand all lines: core/tests/javascript/workers/worker.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ def runtime_version():
44
return sys.version
55

66

7-
__export__ = ['runtime_version']
7+
__export__ = ["runtime_version"]

‎core/tests/manual/fs/index.py

Copy file name to clipboardExpand all lines: core/tests/manual/fs/index.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
await fs.mount("/persistent")
99

1010
print(
11-
RUNNING_IN_WORKER and "Worker" or "Main",
11+
(RUNNING_IN_WORKER and "Worker") or "Main",
1212
os.listdir("/persistent"),
1313
)
1414

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.