Skip to content

Re ruff #2292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 20, 2025
Merged

Re ruff #2292

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
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ repos:
additional_dependencies:
- tomli

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.9.6
hooks:
- id: ruff

- repo: https://github.com/hoodmane/pyscript-prettier-precommit
rev: "v3.0.0-alpha.6"
hooks:
Expand Down
17 changes: 9 additions & 8 deletions core/src/stdlib/pyscript/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ def _eval_formatter(obj, print_method):
"""
if print_method == "__repr__":
return repr(obj)
elif hasattr(obj, print_method):
if hasattr(obj, print_method):
if print_method == "savefig":
buf = io.BytesIO()
obj.savefig(buf, format="png")
buf.seek(0)
return base64.b64encode(buf.read()).decode("utf-8")
return getattr(obj, print_method)()
elif print_method == "_repr_mimebundle_":
if print_method == "_repr_mimebundle_":
return {}, {}
return None

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

if output is None:
continue
elif mime_type not in _MIME_RENDERERS:
if mime_type not in _MIME_RENDERERS:
not_available.append(mime_type)
continue
break
Expand Down Expand Up @@ -149,9 +149,11 @@ def display(*values, target=None, append=True):
if target is None:
target = current_target()
elif not isinstance(target, str):
raise TypeError(f"target must be str or None, not {target.__class__.__name__}")
msg = f"target must be str or None, not {target.__class__.__name__}"
raise TypeError(msg)
elif target == "":
raise ValueError("Cannot have an empty target")
msg = "Cannot have an empty target"
raise ValueError(msg)
elif target.startswith("#"):
# note: here target is str and not None!
# align with @when behavior
Expand All @@ -161,9 +163,8 @@ def display(*values, target=None, append=True):

# If target cannot be found on the page, a ValueError is raised
if element is None:
raise ValueError(
f"Invalid selector with id={target}. Cannot be found in the page."
)
msg = f"Invalid selector with id={target}. Cannot be found in the page."
raise ValueError(msg)

# if element is a <script type="py">, it has a 'target' attribute which
# points to the visual element holding the displayed values. In that case,
Expand Down
6 changes: 4 additions & 2 deletions core/src/stdlib/pyscript/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ def add_listener(self, listener):
if listener not in self._listeners:
self._listeners.append(listener)
else:
raise ValueError("Listener must be callable or awaitable.")
msg = "Listener must be callable or awaitable."
raise ValueError(msg)

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

Expand Down
6 changes: 3 additions & 3 deletions core/src/stdlib/pyscript/flatted.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def _object_keys(value):


def _is_array(value):
return isinstance(value, list) or isinstance(value, tuple)
return isinstance(value, (list, tuple))


def _is_object(value):
Expand Down Expand Up @@ -60,10 +60,10 @@ def _loop(keys, input, known, output):


def _ref(key, value, input, known, output):
if _is_array(value) and not value in known:
if _is_array(value) and value not in known:
known.append(value)
value = _loop(_array_keys(value), input, known, value)
elif _is_object(value) and not value in known:
elif _is_object(value) and value not in known:
known.append(value)
value = _loop(_object_keys(value), input, known, value)

Expand Down
1 change: 1 addition & 0 deletions core/src/stdlib/pyscript/magic_js.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __getattr__(self, field):
# avoid pyodide looking for non existent fields
if not field.startswith("_"):
return getattr(getattr(js_modules, self.name), field)
return None


# generate N modules in the system that will proxy the real value
Expand Down
3 changes: 1 addition & 2 deletions core/src/stdlib/pyscript/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ async def load(cls, audio=False, video=True):
for k in video:
setattr(options.video, k, to_js(video[k]))

stream = await window.navigator.mediaDevices.getUserMedia(options)
return stream
return await window.navigator.mediaDevices.getUserMedia(options)

async def get_stream(self):
key = self.kind.replace("input", "").replace("output", "")
Expand Down
10 changes: 6 additions & 4 deletions core/src/stdlib/pyscript/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ def _to_idb(value):
if isinstance(value, (bool, float, int, str, list, dict, tuple)):
return _stringify(["generic", value])
if isinstance(value, bytearray):
return _stringify(["bytearray", [v for v in value]])
return _stringify(["bytearray", list(value)])
if isinstance(value, memoryview):
return _stringify(["memoryview", [v for v in value]])
raise TypeError(f"Unexpected value: {value}")
return _stringify(["memoryview", list(value)])
msg = f"Unexpected value: {value}"
raise TypeError(msg)


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

async def storage(name="", storage_class=Storage):
if not name:
raise ValueError("The storage name must be defined")
msg = "The storage name must be defined"
raise ValueError(msg)
return storage_class(await _storage(f"@pyscript/{name}"))
2 changes: 1 addition & 1 deletion core/src/stdlib/pyscript/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def as_bytearray(buffer):
ui8a = js.Uint8Array.new(buffer)
size = ui8a.length
ba = bytearray(size)
for i in range(0, size):
for i in range(size):
ba[i] = ui8a[i]
return ba

Expand Down
47 changes: 27 additions & 20 deletions core/src/stdlib/pyscript/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

# `when` is not used in this module. It is imported here save the user an additional
# import (i.e. they can get what they need from `pyscript.web`).
from pyscript import document, when, Event # NOQA

# from __future__ import annotations # CAUTION: This is not supported in MicroPython.

from pyscript import document, when, Event # noqa: F401
from pyscript.ffi import create_proxy


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

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

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

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

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

except AttributeError:
# Nope! This is not an element or a NodeList.
raise TypeError(
msg = (
f'Element "{item}" is a proxy object, "'
f"but not a valid element or a NodeList."
)
raise TypeError(msg)

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

new_option = option(**kwargs)

if before:
if isinstance(before, Element):
before = before._dom_element
if before and isinstance(before, Element):
before = before._dom_element

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

Expand Down Expand Up @@ -463,7 +468,7 @@ def __init__(
)

for child in list(args) + (children or []):
if isinstance(child, Element) or isinstance(child, ElementCollection):
if isinstance(child, (Element, ElementCollection)):
self.append(child)

else:
Expand Down Expand Up @@ -493,14 +498,13 @@ def __eq__(self, other):
)

def __iter__(self):
for class_name in self._all_class_names():
yield class_name
yield from self._all_class_names()

def __len__(self):
return len(self._all_class_names())

def __repr__(self):
return f"ClassesCollection({repr(self._collection)})"
return f"ClassesCollection({self._collection!r})"

def __str__(self):
return " ".join(self._all_class_names())
Expand Down Expand Up @@ -553,7 +557,7 @@ def __setitem__(self, key, value):
element.style[key] = value

def __repr__(self):
return f"StyleCollection({repr(self._collection)})"
return f"StyleCollection({self._collection!r})"

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

elif isinstance(key, slice):
if isinstance(key, slice):
return ElementCollection(self._elements[key])

return self.find(key)
Expand Down Expand Up @@ -1125,7 +1129,8 @@ def snap(

elif isinstance(to, Element):
if to.tag != "canvas":
raise TypeError("Element to snap to must be a canvas.")
msg = "Element to snap to must be a canvas."
raise TypeError(msg)

elif getattr(to, "tagName", "") == "CANVAS":
to = canvas(dom_element=to)
Expand All @@ -1134,10 +1139,12 @@ def snap(
elif isinstance(to, str):
nodelist = document.querySelectorAll(to) # NOQA
if nodelist.length == 0:
raise TypeError("No element with selector {to} to snap to.")
msg = "No element with selector {to} to snap to."
raise TypeError(msg)

if nodelist[0].tagName != "CANVAS":
raise TypeError("Element to snap to must be a canvas.")
msg = "Element to snap to must be a canvas."
raise TypeError(msg)

to = canvas(dom_element=nodelist[0])

Expand Down
2 changes: 1 addition & 1 deletion core/src/stdlib/pyscript/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __getattr__(self, attr):
return value


class WebSocket(object):
class WebSocket:
CONNECTING = 0
OPEN = 1
CLOSING = 2
Expand Down
8 changes: 5 additions & 3 deletions core/src/stdlib/pyscript/workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ async def create_named_worker(src="", name="", config=None, type="py"):
from json import dumps

if not src:
raise ValueError("Named workers require src")
msg = "Named workers require src"
raise ValueError(msg)

if not name:
raise ValueError("Named workers require a name")
msg = "Named workers require a name"
raise ValueError(msg)

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

if config:
_set(s, "config", isinstance(config, str) and config or dumps(config))
_set(s, "config", (isinstance(config, str) and config) or dumps(config))

_js.document.body.append(s)
return await workers[name]
8 changes: 4 additions & 4 deletions core/tests/javascript/pyodide-cache/index.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy
import matplotlib
import numpy as np
import matplotlib as mpl

# just do something with the packages
print(len(dir(numpy)))
print(len(dir(matplotlib)))
print(len(dir(np)))
print(len(dir(mpl)))
2 changes: 1 addition & 1 deletion core/tests/javascript/workers/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ def runtime_version():
return sys.version


__export__ = ['runtime_version']
__export__ = ["runtime_version"]
2 changes: 1 addition & 1 deletion core/tests/manual/fs/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
await fs.mount("/persistent")

print(
RUNNING_IN_WORKER and "Worker" or "Main",
(RUNNING_IN_WORKER and "Worker") or "Main",
os.listdir("/persistent"),
)

Expand Down
Loading
Loading