Browse Source

add ruff checks

Falko Schindler 1 year ago
parent
commit
f1a5a0e40c

+ 1 - 1
examples/pytest/conftest.py

@@ -1,2 +1,2 @@
 # pylint: disable=wildcard-import,unused-wildcard-import
-from nicegui.testing.conftest import *  # noqa: F401,F403
+from nicegui.testing.conftest import *  # noqa: F403

+ 1 - 1
nicegui/air.py

@@ -71,7 +71,7 @@ class Air:
         @self.relay.on('range-request')
         async def _handle_range_request(data: Dict[str, Any]) -> Dict[str, Any]:
             headers: Dict[str, Any] = data['headers']
-            url = list(u for u in core.app.urls if self.remote_url != u)[0] + data['path']
+            url = next(iter(u for u in core.app.urls if self.remote_url != u)) + data['path']
             data['params']['nicegui_chunk_size'] = 1024
             request = self.client.build_request(
                 data['method'],

+ 3 - 3
nicegui/client.py

@@ -6,7 +6,7 @@ import time
 import uuid
 from contextlib import contextmanager
 from pathlib import Path
-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Iterable, Iterator, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, Iterable, Iterator, List, Optional, Union
 
 from fastapi import Request
 from fastapi.responses import Response
@@ -31,10 +31,10 @@ templates = Jinja2Templates(Path(__file__).parent / 'templates')
 
 
 class Client:
-    page_routes: Dict[Callable[..., Any], str] = {}
+    page_routes: ClassVar[Dict[Callable[..., Any], str]] = {}
     """Maps page builders to their routes."""
 
-    instances: Dict[str, Client] = {}
+    instances: ClassVar[Dict[str, Client]] = {}
     """Maps client IDs to clients."""
 
     auto_index_client: Client

+ 7 - 7
nicegui/element.py

@@ -5,7 +5,7 @@ import inspect
 import re
 from copy import copy, deepcopy
 from pathlib import Path
-from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Sequence, Union, overload
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, Union, overload
 
 from typing_extensions import Self
 
@@ -55,12 +55,12 @@ TAG_PATTERN = re.compile(fr'^({TAG_START_CHAR})({TAG_CHAR})*$')
 
 class Element(Visibility):
     component: Optional[Component] = None
-    libraries: List[Library] = []
-    extra_libraries: List[Library] = []
-    exposed_libraries: List[Library] = []
-    _default_props: Dict[str, Any] = {}
-    _default_classes: List[str] = []
-    _default_style: Dict[str, str] = {}
+    libraries: ClassVar[List[Library]] = []
+    extra_libraries: ClassVar[List[Library]] = []
+    exposed_libraries: ClassVar[List[Library]] = []
+    _default_props: ClassVar[Dict[str, Any]] = {}
+    _default_classes: ClassVar[List[str]] = []
+    _default_style: ClassVar[Dict[str, str]] = {}
 
     def __init__(self, tag: Optional[str] = None, *, _client: Optional[Client] = None) -> None:
         """Generic Element

+ 2 - 2
nicegui/javascript_request.py

@@ -1,11 +1,11 @@
 from __future__ import annotations
 
 import asyncio
-from typing import Any, Dict
+from typing import Any, ClassVar, Dict
 
 
 class JavaScriptRequest:
-    _instances: Dict[str, JavaScriptRequest] = {}
+    _instances: ClassVar[Dict[str, JavaScriptRequest]] = {}
 
     def __init__(self, request_id: str, *, timeout: float) -> None:
         self.request_id = request_id

+ 4 - 4
nicegui/observables.py

@@ -2,7 +2,7 @@ from __future__ import annotations
 
 import abc
 import time
-from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, SupportsIndex, Union
+from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, Set, SupportsIndex, Union
 
 from . import events
 
@@ -50,7 +50,7 @@ class ObservableCollection(abc.ABC):  # noqa: B024
 class ObservableDict(ObservableCollection, dict):
 
     def __init__(self,
-                 data: Dict = None,  # type: ignore
+                 data: Optional[Dict] = None,
                  *,
                  on_change: Optional[Callable] = None,
                  _parent: Optional[ObservableCollection] = None,
@@ -102,7 +102,7 @@ class ObservableDict(ObservableCollection, dict):
 class ObservableList(ObservableCollection, list):
 
     def __init__(self,
-                 data: List = None,  # type: ignore
+                 data: Optional[List] = None,
                  *,
                  on_change: Optional[Callable] = None,
                  _parent: Optional[ObservableCollection] = None,
@@ -164,7 +164,7 @@ class ObservableList(ObservableCollection, list):
 class ObservableSet(ObservableCollection, set):
 
     def __init__(self,
-                 data: set = None,  # type: ignore
+                 data: Optional[Set] = None,
                  *,
                  on_change: Optional[Callable] = None,
                  _parent: Optional[ObservableCollection] = None,

+ 2 - 2
nicegui/slot.py

@@ -1,7 +1,7 @@
 from __future__ import annotations
 
 import asyncio
-from typing import TYPE_CHECKING, Dict, Iterator, List, Optional
+from typing import TYPE_CHECKING, ClassVar, Dict, Iterator, List, Optional
 
 from typing_extensions import Self
 
@@ -12,7 +12,7 @@ if TYPE_CHECKING:
 
 
 class Slot:
-    stacks: Dict[int, List[Slot]] = {}
+    stacks: ClassVar[Dict[int, List[Slot]]] = {}
     """Maps asyncio task IDs to slot stacks, which keep track of the current slot in each task."""
 
     def __init__(self, parent: Element, name: str, template: Optional[str] = None) -> None:

+ 1 - 1
nicegui/welcome.py

@@ -21,7 +21,7 @@ async def collect_urls() -> None:
         return
     ips = set((await run.io_bound(_get_all_ips)) if host == '0.0.0.0' else [])
     ips.discard('127.0.0.1')
-    urls = [(f'http://{ip}:{port}' if port != '80' else f'http://{ip}') for ip in ['localhost'] + sorted(ips)]
+    urls = [(f'http://{ip}:{port}' if port != '80' else f'http://{ip}') for ip in ['localhost', *sorted(ips)]]
     core.app.urls.update(urls)
     if len(urls) >= 2:
         urls[-1] = 'and ' + urls[-1]

+ 1 - 0
pyproject.toml

@@ -89,6 +89,7 @@ select = [
     "B",  # bugbear
     "F",  # pyflakes
     "UP", # pyupgrade
+    "RUF", # ruff
 ]
 fixable = [
     "I",  # isort

+ 1 - 1
tests/conftest.py

@@ -1,2 +1,2 @@
 # pylint: disable=wildcard-import,unused-wildcard-import
-from nicegui.testing.conftest import *  # noqa: F401,F403
+from nicegui.testing.conftest import *  # noqa: F403

+ 3 - 3
tests/test_binding.py

@@ -1,4 +1,4 @@
-from typing import Dict
+from typing import Dict, Optional, Tuple
 
 from selenium.webdriver.common.keys import Keys
 
@@ -8,13 +8,13 @@ from nicegui.testing import Screen
 
 def test_ui_select_with_tuple_as_key(screen: Screen):
     class Model:
-        selection = None
+        selection: Optional[Tuple[int, int]] = None
     data = Model()
     options = {
         (2, 1): 'option A',
         (1, 2): 'option B',
     }
-    data.selection = list(options.keys())[0]
+    data.selection = next(iter(options))
     ui.select(options).bind_value(data, 'selection')
 
     screen.open('/')

+ 1 - 1
tests/test_events.py

@@ -169,7 +169,7 @@ def test_server_side_validation(screen: Screen, attribute: Literal['disabled', '
     else:
         b.set_visibility(False)
     ui.button('Hack', on_click=lambda: ui.run_javascript(f'''
-        getElement({b.id}).$emit("click", {{"id": {b.id}, "listener_id": "{list(b._event_listeners.keys())[0]}"}});
+        getElement({b.id}).$emit("click", {{"id": {b.id}, "listener_id": "{next(iter(b._event_listeners))}"}});
     '''))  # pylint: disable=protected-access
 
     screen.open('/')

+ 1 - 1
tests/test_storage.py

@@ -222,7 +222,7 @@ def test_clear_tab_storage(screen: Screen):
 
     tab_storages = app.storage._tabs  # pylint: disable=protected-access
     assert len(tab_storages) == 1
-    assert list(tab_storages.values())[0] == {'test': '123'}
+    assert next(iter(tab_storages.values())) == {'test': '123'}
 
     screen.click('clear')
     screen.wait(0.5)

+ 1 - 1
website/documentation/reference.py

@@ -82,7 +82,7 @@ def _generate_method_signature_description(method: Callable) -> str:
             param_type = inspect.formatannotation(param.annotation)
             param_string += f''': {param_type.strip("'")}'''
         if param.default != inspect.Parameter.empty:
-            param_string += ' = [...]' if callable(param.default) else f' = {repr(param.default)}'
+            param_string += ' = [...]' if callable(param.default) else f' = {param.default!r}'
         if param.kind == inspect.Parameter.VAR_POSITIONAL:
             param_string = f'*{param_string}'
         param_strings.append(param_string)