Sfoglia il codice sorgente

fix mypy and pylint issues on functions module

Falko Schindler 1 anno fa
parent
commit
76f387d67b

+ 1 - 0
.vscode/settings.json

@@ -8,6 +8,7 @@
     "--disable=C0103", // Invalid name (e.g., variable/function/class naming conventions)
     "--disable=C0111", // Missing docstring (in function/class/method)
     "--disable=C0301", // Line too long (exceeds character limit)
+    "--disable=C0302", // Too many lines in module
     "--disable=R0801", // Similar lines in files
     "--disable=R0902", // Too many instance attributes
     "--disable=R0903", // Too few public methods

+ 3 - 2
fetch_tailwind.py

@@ -80,6 +80,7 @@ for li in soup.select('li[class="mt-12 lg:mt-8"]'):
 
 for file in (Path(__file__).parent / 'nicegui' / 'tailwind_types').glob('*.py'):
     file.unlink()
+(Path(__file__).parent / 'nicegui' / 'tailwind_types' / '__init__.py').touch()
 for property_ in properties:
     if not property_.members:
         continue
@@ -127,11 +128,11 @@ with (Path(__file__).parent / 'nicegui' / 'tailwind.py').open('w') as f:
     f.write('    def __call__(self, *classes: str) -> Tailwind:\n')
     f.write('        ...\n')
     f.write('\n')
-    f.write('    def __call__(self, *args) -> Tailwind:\n')
+    f.write('    def __call__(self, *args) -> Tailwind:  # type: ignore\n')
     f.write('        if not args:\n')
     f.write('            return self\n')
     f.write('        if isinstance(args[0], Tailwind):\n')
-    f.write('            args[0].apply(self.element)\n')
+    f.write('            args[0].apply(self.element)  # type: ignore\n')
     f.write('        else:\n')
     f.write("            self.element.classes(' '.join(args))\n")
     f.write('        return self\n')

+ 3 - 1
nicegui/background_tasks.py

@@ -1,4 +1,6 @@
 """inspired from https://quantlane.com/blog/ensure-asyncio-task-exceptions-get-logged/"""
+from __future__ import annotations
+
 import asyncio
 import sys
 from typing import Awaitable, Dict, Set, TypeVar
@@ -14,7 +16,7 @@ lazy_tasks_running: Dict[str, asyncio.Task] = {}
 lazy_tasks_waiting: Dict[str, Awaitable[T]] = {}
 
 
-def create(coroutine: Awaitable[T], *, name: str = 'unnamed task') -> 'asyncio.Task[T]':
+def create(coroutine: Awaitable[T], *, name: str = 'unnamed task') -> asyncio.Task[T]:
     """Wraps a loop.create_task call and ensures there is an exception handler added to the task.
 
     If the task raises an exception, it is logged and handled by the global exception handlers.

+ 1 - 1
nicegui/client.py

@@ -57,7 +57,7 @@ class Client:
     @property
     def ip(self) -> Optional[str]:
         """Return the IP address of the client, or None if the client is not connected."""
-        return self.environ.get('asgi.scope')['client'][0] if self.environ else None
+        return self.environ['asgi.scope']['client'][0] if self.environ else None  # pylint: disable=unsubscriptable-object
 
     @property
     def has_socket_connection(self) -> bool:

+ 4 - 2
nicegui/elements/select.py

@@ -58,7 +58,8 @@ class Select(ChoiceElement, DisableableElement, component='select.js'):
         self.update()
 
     def _event_args_to_value(self, e: GenericEventArguments) -> Any:
-        if self.multiple:  # pylint: disable=no-else-return
+        # pylint: disable=no-else-return
+        if self.multiple:
             if e.args is None:
                 return []
             assert isinstance(e.args, list)
@@ -69,7 +70,8 @@ class Select(ChoiceElement, DisableableElement, component='select.js'):
             return self._values[e.args['value']]
 
     def _value_to_model_value(self, value: Any) -> Any:
-        if self.multiple:  # pylint: disable=no-else-return
+        # pylint: disable=no-else-return
+        if self.multiple:
             result = []
             for item in value or []:
                 try:

+ 0 - 0
nicegui/functions/__init__.py


+ 1 - 1
nicegui/functions/download.py

@@ -1,7 +1,7 @@
 from pathlib import Path
 from typing import Optional, Union
 
-from .. import globals, helpers
+from .. import globals, helpers  # pylint: disable=redefined-builtin
 
 
 def download(src: Union[str, Path], filename: Optional[str] = None) -> None:

+ 1 - 1
nicegui/functions/html.py

@@ -1,4 +1,4 @@
-from .. import globals
+from .. import globals  # pylint: disable=redefined-builtin
 
 
 def add_body_html(code: str) -> None:

+ 1 - 1
nicegui/functions/javascript.py

@@ -1,6 +1,6 @@
 from typing import Any, Optional
 
-from .. import globals
+from .. import globals  # pylint: disable=redefined-builtin
 
 
 async def run_javascript(code: str, *,

+ 20 - 3
nicegui/functions/notify.py

@@ -1,6 +1,6 @@
 from typing import Any, Literal, Optional, Union
 
-from .. import globals, outbox
+from .. import globals, outbox  # pylint: disable=redefined-builtin
 
 ARG_MAP = {
     'close_button': 'closeBtn',
@@ -8,10 +8,27 @@ ARG_MAP = {
 }
 
 
+# pylint: disable=unused-argument
 def notify(message: Any, *,
-           position: Literal['top-left', 'top-right', 'bottom-left', 'bottom-right', 'top', 'bottom', 'left', 'right', 'center'] = 'bottom',
+           position: Literal[
+               'top-left',
+               'top-right',
+               'bottom-left',
+               'bottom-right',
+               'top',
+               'bottom',
+               'left',
+               'right',
+               'center',
+           ] = 'bottom',
            close_button: Union[bool, str] = False,
-           type: Optional[Literal['positive', 'negative', 'warning', 'info', 'ongoing']] = None,
+           type: Optional[Literal[  # pylint: disable=redefined-builtin
+               'positive',
+               'negative',
+               'warning',
+               'info',
+               'ongoing',
+           ]] = None,
            color: Optional[str] = None,
            multi_line: bool = False,
            **kwargs: Any,

+ 2 - 2
nicegui/functions/open.py

@@ -1,9 +1,9 @@
 from typing import Any, Callable, Union
 
-from .. import globals
+from .. import globals  # pylint: disable=redefined-builtin
 
 
-def open(target: Union[Callable[..., Any], str], new_tab: bool = False) -> None:
+def open(target: Union[Callable[..., Any], str], new_tab: bool = False) -> None:  # pylint: disable=redefined-builtin
     """Open
 
     Can be used to programmatically trigger redirects for a specific client.

+ 4 - 3
nicegui/functions/refreshable.py

@@ -3,10 +3,10 @@ from typing import Any, Awaitable, Callable, Dict, List, Tuple, Union
 
 from typing_extensions import Self
 
-from .. import background_tasks, globals
+from .. import background_tasks, globals  # pylint: disable=redefined-builtin
+from ..dataclasses import KWONLY_SLOTS
 from ..element import Element
 from ..helpers import is_coroutine_function
-from .dataclasses import KWONLY_SLOTS
 
 
 @dataclass(**KWONLY_SLOTS)
@@ -17,6 +17,7 @@ class RefreshableTarget:
     kwargs: Dict[str, Any]
 
     def run(self, func: Callable[..., Any]) -> Union[None, Awaitable]:
+        # pylint: disable=no-else-return
         if is_coroutine_function(func):
             async def wait_for_result() -> None:
                 with self.container:
@@ -83,7 +84,7 @@ class refreshable:
                 if 'got multiple values for argument' in str(e):
                     function = str(e).split()[0].split('.')[-1]
                     parameter = str(e).split()[-1]
-                    raise Exception(f'{parameter} needs to be consistently passed to {function} '
+                    raise TypeError(f'{parameter} needs to be consistently passed to {function} '
                                     'either as positional or as keyword argument') from e
                 raise
             if is_coroutine_function(self.func):

+ 9 - 9
nicegui/functions/timer.py

@@ -2,7 +2,7 @@ import asyncio
 import time
 from typing import Any, Awaitable, Callable, Optional
 
-from .. import background_tasks, globals
+from .. import background_tasks, globals  # pylint: disable=redefined-builtin
 from ..binding import BindableProperty
 from ..slot import Slot
 
@@ -115,14 +115,14 @@ class Timer:
         assert self.slot is not None
         if self.slot.parent.client.shared:
             return True
-        else:
-            # ignore served pages which do not reconnect to backend (eg. monitoring requests, scrapers etc.)
-            try:
-                await self.slot.parent.client.connected(timeout=timeout)
-                return True
-            except TimeoutError:
-                globals.log.error(f'Timer cancelled because client is not connected after {timeout} seconds')
-                return False
+
+        # ignore served pages which do not reconnect to backend (e.g. monitoring requests, scrapers etc.)
+        try:
+            await self.slot.parent.client.connected(timeout=timeout)
+            return True
+        except TimeoutError:
+            globals.log.error(f'Timer cancelled because client is not connected after {timeout} seconds')
+            return False
 
     def _cleanup(self) -> None:
         self.slot = None

+ 2 - 2
nicegui/tailwind.py

@@ -188,11 +188,11 @@ class Tailwind:
     def __call__(self, *classes: str) -> Tailwind:
         ...
 
-    def __call__(self, *args) -> Tailwind:
+    def __call__(self, *args) -> Tailwind:  # type: ignore
         if not args:
             return self
         if isinstance(args[0], Tailwind):
-            args[0].apply(self.element)
+            args[0].apply(self.element)  # type: ignore
         else:
             self.element.classes(' '.join(args))
         return self

+ 0 - 0
nicegui/tailwind_types/__init__.py