Explorar o código

consistently use prefix "on_" for registering handlers only (fixes #1326)

Falko Schindler hai 1 ano
pai
achega
d9d65d0647

+ 4 - 3
examples/custom_binding/main.py

@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 import random
-from typing import Optional
+from typing import Optional, Self, cast
 
 from nicegui import ui
 from nicegui.binding import BindableProperty, bind_from
@@ -10,13 +10,14 @@ class colorful_label(ui.label):
     """A label with a bindable background color."""
 
     # This class variable defines what happens when the background property changes.
-    background = BindableProperty(on_change=lambda sender, value: sender.on_background_change(value))
+    background = BindableProperty(
+        on_change=lambda sender, value: cast(Self, sender)._handle_background_change(value))
 
     def __init__(self, text: str = '') -> None:
         super().__init__(text)
         self.background: Optional[str] = None  # initialize the background property
 
-    def on_background_change(self, bg_class: str) -> None:
+    def _handle_background_change(self, bg_class: str) -> None:
         """Update the classes of the label when the background property changes."""
         self._classes = [c for c in self._classes if not c.startswith('bg-')]
         self._classes.append(bg_class)

+ 2 - 2
examples/docker_image/app/main.py

@@ -9,9 +9,9 @@ def index():
         .classes('w-96').bind_value(app.storage.user, 'note')
 
 
-def on_shutdown():
+def handle_shutdown():
     print('Shutdown has been initiated!')
 
 
-app.on_shutdown(on_shutdown)
+app.on_shutdown(handle_shutdown)
 ui.run(storage_secret=os.environ['STORAGE_SECRET'])

+ 2 - 2
examples/lightbox/main.py

@@ -13,7 +13,7 @@ class Lightbox:
 
     def __init__(self) -> None:
         with ui.dialog().props('maximized').classes('bg-black') as self.dialog:
-            ui.keyboard(self._on_key)
+            ui.keyboard(self._handle_key)
             self.large_image = ui.image().props('no-spinner fit=scale-down')
         self.image_list: List[str] = []
 
@@ -23,7 +23,7 @@ class Lightbox:
         with ui.button(on_click=lambda: self._open(orig_url)).props('flat dense square'):
             return ui.image(thumb_url)
 
-    def _on_key(self, event_args: events.KeyEventArguments) -> None:
+    def _handle_key(self, event_args: events.KeyEventArguments) -> None:
         if not event_args.action.keydown:
             return
         if event_args.key.escape:

+ 2 - 2
main.py

@@ -33,10 +33,10 @@ app.add_static_files('/fonts', str(Path(__file__).parent / 'website' / 'fonts'))
 app.add_static_files('/static', str(Path(__file__).parent / 'website' / 'static'))
 
 if True:  # HACK: prevent the page from scrolling when closing a dialog (#1404)
-    def on_dialog_value_change(sender, value, on_value_change=ui.dialog._on_value_change) -> None:
+    def _handle_value_change(sender, value, on_value_change=ui.dialog._handle_value_change) -> None:
         ui.query('html').classes(**{'add' if value else 'remove': 'has-dialog'})
         on_value_change(sender, value)
-    ui.dialog._on_value_change = on_dialog_value_change
+    ui.dialog._handle_value_change = _handle_value_change
 
 
 @app.get('/logo.png')

+ 9 - 9
nicegui/air.py

@@ -22,7 +22,7 @@ class Air:
         self.connecting = False
 
         @self.relay.on('http')
-        async def on_http(data: Dict[str, Any]) -> Dict[str, Any]:
+        async def _handle_http(data: Dict[str, Any]) -> Dict[str, Any]:
             headers: Dict[str, Any] = data['headers']
             headers.update({'Accept-Encoding': 'identity', 'X-Forwarded-Prefix': data['prefix']})
             url = 'http://test' + data['path']
@@ -52,16 +52,16 @@ class Air:
             }
 
         @self.relay.on('ready')
-        def on_ready(data: Dict[str, Any]) -> None:
+        def _handle_ready(data: Dict[str, Any]) -> None:
             globals.app.urls.add(data['device_url'])
             print(f'NiceGUI is on air at {data["device_url"]}', flush=True)
 
         @self.relay.on('error')
-        def on_error(data: Dict[str, Any]) -> None:
+        def _handleerror(data: Dict[str, Any]) -> None:
             print('Error:', data['message'], flush=True)
 
         @self.relay.on('handshake')
-        def on_handshake(data: Dict[str, Any]) -> bool:
+        def _handle_handshake(data: Dict[str, Any]) -> bool:
             client_id = data['client_id']
             if client_id not in globals.clients:
                 return False
@@ -72,7 +72,7 @@ class Air:
             return True
 
         @self.relay.on('client_disconnect')
-        def on_disconnect(data: Dict[str, Any]) -> None:
+        def _handle_disconnect(data: Dict[str, Any]) -> None:
             client_id = data['client_id']
             if client_id not in globals.clients:
                 return
@@ -80,7 +80,7 @@ class Air:
             client.disconnect_task = background_tasks.create(handle_disconnect(client))
 
         @self.relay.on('event')
-        def on_event(data: Dict[str, Any]) -> None:
+        def _handle_event(data: Dict[str, Any]) -> None:
             client_id = data['client_id']
             if client_id not in globals.clients:
                 return
@@ -90,7 +90,7 @@ class Air:
             handle_event(client, data['msg'])
 
         @self.relay.on('javascript_response')
-        def on_javascript_response(data: Dict[str, Any]) -> None:
+        def _handle_javascript_response(data: Dict[str, Any]) -> None:
             client_id = data['client_id']
             if client_id not in globals.clients:
                 return
@@ -98,12 +98,12 @@ class Air:
             handle_javascript_response(client, data['msg'])
 
         @self.relay.on('out_of_time')
-        async def on_move() -> None:
+        async def _handle_out_of_time() -> None:
             print('Sorry, you have reached the time limit of this NiceGUI On Air preview.', flush=True)
             await self.connect()
 
         @self.relay.on('reconnect')
-        async def on_reconnect(_: Dict[str, Any]) -> None:
+        async def _handle_reconnect(_: Dict[str, Any]) -> None:
             await self.connect()
 
     async def connect(self) -> None:

+ 3 - 3
nicegui/binding.py

@@ -123,7 +123,7 @@ def bind(self_obj: Any, self_name: str, other_obj: Any, other_name: str, *,
 class BindableProperty:
 
     def __init__(self, on_change: Optional[Callable[..., Any]] = None) -> None:
-        self.on_change = on_change
+        self._change_handler = on_change
 
     def __set_name__(self, _, name: str) -> None:
         self.name = name  # pylint: disable=attribute-defined-outside-init
@@ -139,8 +139,8 @@ class BindableProperty:
         setattr(owner, '___' + self.name, value)
         bindable_properties[(id(owner), self.name)] = owner
         _propagate(owner, self.name)
-        if value_changed and self.on_change is not None:
-            self.on_change(owner, value)
+        if value_changed and self._change_handler is not None:
+            self._change_handler(owner, value)
 
 
 def remove(objects: Iterable[Any], type_: Type) -> None:

+ 1 - 1
nicegui/client.py

@@ -172,7 +172,7 @@ class Client:
         for element_id in element_ids:
             del self.elements[element_id]
         for element in elements:
-            element._on_delete()  # pylint: disable=protected-access
+            element._handle_delete()  # pylint: disable=protected-access
             element._deleted = True  # pylint: disable=protected-access
             outbox.enqueue_delete(element)
 

+ 1 - 1
nicegui/element.py

@@ -422,7 +422,7 @@ class Element(Visibility):
         assert self.parent_slot is not None
         self.parent_slot.children.remove(self)
 
-    def _on_delete(self) -> None:
+    def _handle_delete(self) -> None:
         """Called when the element is deleted.
 
         This method can be overridden in subclasses to perform cleanup tasks.

+ 2 - 2
nicegui/elements/carousel.py

@@ -35,8 +35,8 @@ class Carousel(ValueElement):
     def _value_to_model_value(self, value: Any) -> Any:
         return value._props['name'] if isinstance(value, CarouselSlide) else value  # pylint: disable=protected-access
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         names = [slide._props['name'] for slide in self]  # pylint: disable=protected-access
         for i, slide in enumerate(self):
             done = i < names.index(value) if value in names else False

+ 2 - 2
nicegui/elements/color_input.py

@@ -46,8 +46,8 @@ class ColorInput(ValueElement, DisableableElement):
             self.picker.set_color(self.value)
         self.picker.open()
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         self._update_preview()
 
     def _update_preview(self) -> None:

+ 2 - 2
nicegui/elements/dialog.py

@@ -48,8 +48,8 @@ class Dialog(ValueElement):
         self._result = result
         self.submitted.set()
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         if not self.value:
             self._result = None
             self.submitted.set()

+ 2 - 2
nicegui/elements/input.py

@@ -60,7 +60,7 @@ class Input(ValidationElement, DisableableElement, component='input.js'):
         self._props['autocomplete'] = autocomplete
         self.update()
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         if self._send_update_on_value_change:
             self.run_method('updateValue')

+ 1 - 1
nicegui/elements/markdown.py

@@ -31,7 +31,7 @@ class Markdown(ContentElement, component='markdown.js'):
             self._props['use_mermaid'] = True
             self.libraries.append(Mermaid.exposed_libraries[0])
 
-    def on_content_change(self, content: str) -> None:
+    def _handle_content_change(self, content: str) -> None:
         html = prepare_content(content, extras=' '.join(self.extras))
         if self._props.get('innerHTML') != html:
             self._props['innerHTML'] = html

+ 1 - 1
nicegui/elements/mermaid.py

@@ -17,6 +17,6 @@ class Mermaid(ContentElement,
         """
         super().__init__(content=content)
 
-    def on_content_change(self, content: str) -> None:
+    def _handle_content_change(self, content: str) -> None:
         self._props[self.CONTENT_PROP] = content.strip()
         self.run_method('update', content.strip())

+ 5 - 4
nicegui/elements/mixins/content_element.py

@@ -1,6 +1,6 @@
 from typing import Any, Callable
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
@@ -8,12 +8,13 @@ from ...element import Element
 
 class ContentElement(Element):
     CONTENT_PROP = 'innerHTML'
-    content = BindableProperty(on_change=lambda sender, content: sender.on_content_change(content))
+    content = BindableProperty(
+        on_change=lambda sender, content: cast(Self, sender)._handle_content_change(content))  # pylint: disable=protected-access
 
     def __init__(self, *, content: str, **kwargs: Any) -> None:
         super().__init__(**kwargs)
         self.content = content
-        self.on_content_change(content)
+        self._handle_content_change(content)
 
     def bind_content_to(self,
                         target_object: Any,
@@ -72,7 +73,7 @@ class ContentElement(Element):
         """
         self.content = content
 
-    def on_content_change(self, content: str) -> None:
+    def _handle_content_change(self, content: str) -> None:
         """Called when the content of this element changes.
 
         :param content: The new content.

+ 4 - 3
nicegui/elements/mixins/disableable_element.py

@@ -1,13 +1,14 @@
 from typing import Any, Callable
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
 
 
 class DisableableElement(Element):
-    enabled = BindableProperty(on_change=lambda sender, value: sender.on_enabled_change(value))
+    enabled = BindableProperty(
+        on_change=lambda sender, value: cast(Self, sender)._handle_enabled_change(value))  # pylint: disable=protected-access
 
     def __init__(self, **kwargs: Any) -> None:
         super().__init__(**kwargs)
@@ -83,7 +84,7 @@ class DisableableElement(Element):
         """Set the enabled state of the element."""
         self.enabled = value
 
-    def on_enabled_change(self, enabled: bool) -> None:
+    def _handle_enabled_change(self, enabled: bool) -> None:
         """Called when the element is enabled or disabled.
 
         :param enabled: The new state.

+ 4 - 3
nicegui/elements/mixins/filter_element.py

@@ -1,6 +1,6 @@
 from typing import Any, Callable, Optional
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
@@ -8,7 +8,8 @@ from ...element import Element
 
 class FilterElement(Element):
     FILTER_PROP = 'filter'
-    filter = BindableProperty(on_change=lambda sender, filter: sender.on_filter_change(filter))
+    filter = BindableProperty(
+        on_change=lambda sender, filter: cast(Self, sender)._handle_filter_change(filter))  # pylint: disable=protected-access
 
     def __init__(self, *, filter: Optional[str] = None, **kwargs: Any) -> None:  # pylint: disable=redefined-builtin
         super().__init__(**kwargs)
@@ -72,7 +73,7 @@ class FilterElement(Element):
         """
         self.filter = filter_
 
-    def on_filter_change(self, filter_: str) -> None:
+    def _handle_filter_change(self, filter_: str) -> None:
         """Called when the filter of this element changes.
 
         :param filter: The new filter.

+ 4 - 3
nicegui/elements/mixins/name_element.py

@@ -1,13 +1,14 @@
 from typing import Any, Callable
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
 
 
 class NameElement(Element):
-    name = BindableProperty(on_change=lambda sender, name: sender.on_name_change(name))
+    name = BindableProperty(
+        on_change=lambda sender, name: cast(Self, sender)._handle_name_change(name))  # pylint: disable=protected-access
 
     def __init__(self, *, name: str, **kwargs: Any) -> None:
         super().__init__(**kwargs)
@@ -71,7 +72,7 @@ class NameElement(Element):
         """
         self.name = name
 
-    def on_name_change(self, name: str) -> None:
+    def _handle_name_change(self, name: str) -> None:
         """Called when the name of this element changes.
 
         :param name: The new name.

+ 4 - 3
nicegui/elements/mixins/source_element.py

@@ -1,7 +1,7 @@
 from pathlib import Path
 from typing import Any, Callable, Union
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ... import globals  # pylint: disable=redefined-builtin
 from ...binding import BindableProperty, bind, bind_from, bind_to
@@ -10,7 +10,8 @@ from ...helpers import is_file
 
 
 class SourceElement(Element):
-    source = BindableProperty(on_change=lambda sender, source: sender.on_source_change(source))
+    source = BindableProperty(
+        on_change=lambda sender, source: cast(Self, sender)._handle_source_change(source))  # pylint: disable=protected-access
 
     def __init__(self, *, source: Union[str, Path], **kwargs: Any) -> None:
         super().__init__(**kwargs)
@@ -76,7 +77,7 @@ class SourceElement(Element):
         """
         self.source = source
 
-    def on_source_change(self, source: Union[str, Path]) -> None:
+    def _handle_source_change(self, source: Union[str, Path]) -> None:
         """Called when the source of this element changes.
 
         :param source: The new source.

+ 4 - 3
nicegui/elements/mixins/text_element.py

@@ -1,13 +1,14 @@
 from typing import Any, Callable
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
 
 
 class TextElement(Element):
-    text = BindableProperty(on_change=lambda sender, text: sender.on_text_change(text))
+    text = BindableProperty(
+        on_change=lambda sender, text: cast(Self, sender)._handle_text_change(text))  # pylint: disable=protected-access
 
     def __init__(self, *, text: str, **kwargs: Any) -> None:
         super().__init__(**kwargs)
@@ -71,7 +72,7 @@ class TextElement(Element):
         """
         self.text = text
 
-    def on_text_change(self, text: str) -> None:
+    def _handle_text_change(self, text: str) -> None:
         """Called when the text of this element changes.
 
         :param text: The new text.

+ 2 - 2
nicegui/elements/mixins/validation_element.py

@@ -26,6 +26,6 @@ class ValidationElement(ValueElement):
             self._error = None
             self.props(remove='error')
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         self.validate()

+ 6 - 5
nicegui/elements/mixins/value_element.py

@@ -1,6 +1,6 @@
 from typing import Any, Callable, Optional
 
-from typing_extensions import Self
+from typing_extensions import Self, cast
 
 from ...binding import BindableProperty, bind, bind_from, bind_to
 from ...element import Element
@@ -10,7 +10,8 @@ from ...events import GenericEventArguments, ValueChangeEventArguments, handle_e
 class ValueElement(Element):
     VALUE_PROP: str = 'model-value'
     LOOPBACK: bool = True
-    value = BindableProperty(on_change=lambda sender, value: sender.on_value_change(value))
+    value = BindableProperty(
+        on_change=lambda sender, value: cast(Self, sender)._handle_value_change(value))  # pylint: disable=protected-access
 
     def __init__(self, *,
                  value: Any,
@@ -23,7 +24,7 @@ class ValueElement(Element):
         self._props[self.VALUE_PROP] = self._value_to_model_value(value)
         self._props['loopback'] = self.LOOPBACK
         self._send_update_on_value_change = True
-        self.change_handler = on_value_change
+        self._change_handler = on_value_change
 
         def handle_change(e: GenericEventArguments) -> None:
             self._send_update_on_value_change = self.LOOPBACK
@@ -88,12 +89,12 @@ class ValueElement(Element):
         """
         self.value = value
 
-    def _on_value_change(self, value: Any) -> None:
+    def _handle_value_change(self, value: Any) -> None:
         self._props[self.VALUE_PROP] = self._value_to_model_value(value)
         if self._send_update_on_value_change:
             self.update()
         args = ValueChangeEventArguments(sender=self, client=self.client, value=self._value_to_event_value(value))
-        handle_event(self.change_handler, args)
+        handle_event(self._change_handler, args)
 
     def _event_args_to_value(self, e: GenericEventArguments) -> Any:
         return e.args

+ 3 - 2
nicegui/elements/mixins/visibility.py

@@ -11,7 +11,8 @@ if TYPE_CHECKING:
 
 
 class Visibility:
-    visible = BindableProperty(on_change=lambda sender, visible: sender.on_visibility_change(visible))
+    visible = BindableProperty(
+        on_change=lambda sender, visible: cast(Self, sender)._handle_visibility_change(visible))  # pylint: disable=protected-access
 
     def __init__(self, **kwargs: Any) -> None:
         super().__init__(**kwargs)
@@ -89,7 +90,7 @@ class Visibility:
         """
         self.visible = visible
 
-    def on_visibility_change(self, visible: str) -> None:
+    def _handle_visibility_change(self, visible: str) -> None:
         """Called when the visibility of this element changes.
 
         :param visible: Whether the element should be visible.

+ 7 - 7
nicegui/elements/scene.py

@@ -88,9 +88,9 @@ class Scene(Element,
         self.objects: Dict[str, Object3D] = {}
         self.stack: List[Union[Object3D, SceneObject]] = [SceneObject()]
         self.camera: SceneCamera = SceneCamera()
-        self.on_click = on_click
-        self.on_drag_start = on_drag_start
-        self.on_drag_end = on_drag_end
+        self._click_handler = on_click
+        self._drag_start_handler = on_drag_start
+        self._drag_end_handler = on_drag_end
         self.is_initialized = False
         self.on('init', self._handle_init)
         self.on('click3d', self._handle_click)
@@ -144,7 +144,7 @@ class Scene(Element,
                 z=hit['point']['z'],
             ) for hit in e.args['hits']],
         )
-        handle_event(self.on_click, arguments)
+        handle_event(self._click_handler, arguments)
 
     def _handle_drag(self, e: GenericEventArguments) -> None:
         arguments = SceneDragEventArguments(
@@ -159,7 +159,7 @@ class Scene(Element,
         )
         if arguments.type == 'dragend':
             self.objects[arguments.object_id].move(arguments.x, arguments.y, arguments.z)
-        handle_event(self.on_drag_start if arguments.type == 'dragstart' else self.on_drag_end, arguments)
+        handle_event(self._drag_start_handler if arguments.type == 'dragstart' else self._drag_end_handler, arguments)
 
     def __len__(self) -> int:
         return len(self.objects)
@@ -202,9 +202,9 @@ class Scene(Element,
                         self.camera.look_at_x, self.camera.look_at_y, self.camera.look_at_z,
                         self.camera.up_x, self.camera.up_y, self.camera.up_z, duration)
 
-    def _on_delete(self) -> None:
+    def _handle_delete(self) -> None:
         binding.remove(list(self.objects.values()), Object3D)
-        super()._on_delete()
+        super()._handle_delete()
 
     def delete_objects(self, predicate: Callable[[Object3D], bool] = lambda _: True) -> None:
         """Remove objects from the scene.

+ 2 - 2
nicegui/elements/scroll_area.py

@@ -29,8 +29,8 @@ class ScrollArea(Element):
                 'horizontalContainerSize',
             ])
 
-    def _handle_scroll(self, on_scroll: Optional[Callable[..., Any]], e: GenericEventArguments) -> None:
-        handle_event(on_scroll, ScrollEventArguments(
+    def _handle_scroll(self, handler: Optional[Callable[..., Any]], e: GenericEventArguments) -> None:
+        handle_event(handler, ScrollEventArguments(
             sender=self,
             client=self.client,
             vertical_position=e.args['verticalPosition'],

+ 2 - 2
nicegui/elements/stepper.py

@@ -34,8 +34,8 @@ class Stepper(ValueElement):
     def _value_to_model_value(self, value: Any) -> Any:
         return value._props['name'] if isinstance(value, Step) else value  # pylint: disable=protected-access
 
-    def _on_value_change(self, value: Any) -> None:
-        super()._on_value_change(value)
+    def _handle_value_change(self, value: Any) -> None:
+        super()._handle_value_change(value)
         names = [step._props['name'] for step in self]  # pylint: disable=protected-access
         for i, step in enumerate(self):
             done = i < names.index(value) if value in names else False

+ 2 - 2
nicegui/elements/upload.py

@@ -70,6 +70,6 @@ class Upload(DisableableElement, component='upload.js'):
         """Clear the upload queue."""
         self.run_method('reset')
 
-    def _on_delete(self) -> None:
+    def _handle_delete(self) -> None:
         app.remove_route(self._props['url'])
-        super()._on_delete()
+        super()._handle_delete()

+ 9 - 18
nicegui/nicegui.py

@@ -43,14 +43,12 @@ globals.index_client = Client(page('/'), shared=True).__enter__()  # pylint: dis
 
 
 @app.get('/')
-def index(request: Request) -> Response:
-    """Auto-index page."""
+def _get_index(request: Request) -> Response:
     return globals.index_client.build_response(request)
 
 
 @app.get(f'/_nicegui/{__version__}' + '/libraries/{key:path}')
-def get_library(key: str) -> FileResponse:
-    """Get a library file with a given key."""
+def _get_library(key: str) -> FileResponse:
     is_map = key.endswith('.map')
     dict_key = key[:-4] if is_map else key
     if dict_key in libraries:
@@ -64,8 +62,7 @@ def get_library(key: str) -> FileResponse:
 
 
 @app.get(f'/_nicegui/{__version__}' + '/components/{key:path}')
-def get_component(key: str) -> FileResponse:
-    """Get a component file with a given key."""
+def _get_component(key: str) -> FileResponse:
     if key in js_components and js_components[key].path.exists():
         headers = {'Cache-Control': 'public, max-age=3600'}
         return FileResponse(js_components[key].path, media_type='text/javascript', headers=headers)
@@ -122,8 +119,7 @@ async def handle_shutdown() -> None:
 
 
 @app.exception_handler(404)
-async def exception_handler_404(request: Request, exception: Exception) -> Response:
-    """Handle 404 errors."""
+async def _exception_handler_404(request: Request, exception: Exception) -> Response:
     globals.log.warning(f'{request.url} not found')
     with Client(page('')) as client:
         error_content(404, exception)
@@ -131,8 +127,7 @@ async def exception_handler_404(request: Request, exception: Exception) -> Respo
 
 
 @app.exception_handler(Exception)
-async def exception_handler_500(request: Request, exception: Exception) -> Response:
-    """Handle 500 errors."""
+async def _exception_handler_500(request: Request, exception: Exception) -> Response:
     globals.log.exception(exception)
     with Client(page('')) as client:
         error_content(500, exception)
@@ -140,8 +135,7 @@ async def exception_handler_500(request: Request, exception: Exception) -> Respo
 
 
 @sio.on('handshake')
-def on_handshake(sid: str, client_id: str) -> bool:
-    """Handle the handshake event."""
+def _on_handshake(sid: str, client_id: str) -> bool:
     client = globals.clients.get(client_id)
     if not client:
         return False
@@ -163,8 +157,7 @@ def handle_handshake(client: Client) -> None:
 
 
 @sio.on('disconnect')
-def on_disconnect(sid: str) -> None:
-    """Handle the disconnect event."""
+def _on_disconnect(sid: str) -> None:
     query_bytes: bytearray = sio.get_environ(sid)['asgi.scope']['query_string']
     query = urllib.parse.parse_qs(query_bytes.decode())
     client_id = query['client_id'][0]
@@ -186,8 +179,7 @@ async def handle_disconnect(client: Client) -> None:
 
 
 @sio.on('event')
-def on_event(_: str, msg: Dict) -> None:
-    """Handle a generic event."""
+def _on_event(_: str, msg: Dict) -> None:
     client = globals.clients.get(msg['client_id'])
     if not client or not client.has_socket_connection:
         return
@@ -206,8 +198,7 @@ def handle_event(client: Client, msg: Dict) -> None:
 
 
 @sio.on('javascript_response')
-def on_javascript_response(_: str, msg: Dict) -> None:
-    """Handle a JavaScript response."""
+def _on_javascript_response(_: str, msg: Dict) -> None:
     client = globals.clients.get(msg['client_id'])
     if not client:
         return

+ 2 - 2
tests/test_element_delete.py

@@ -124,9 +124,9 @@ def test_on_delete(screen: Screen):
         def __init__(self, text: str) -> None:
             super().__init__(text)
 
-        def _on_delete(self) -> None:
+        def _handle_delete(self) -> None:
             deleted_labels.append(self.text)
-            super()._on_delete()
+            super()._handle_delete()
 
     with ui.row() as row:
         CustomLabel('Label A')

+ 3 - 3
website/build_search_index.py

@@ -52,7 +52,7 @@ class DocVisitor(ast.NodeVisitor):
         else:
             raise NotImplementedError(f'Unknown function type: {node.func}')
         if function_name in ['heading', 'subheading']:
-            self.on_new_heading()
+            self._handle_new_heading()
             self.current_title = node.args[0].s
         elif function_name == 'markdown':
             if node.args:
@@ -61,7 +61,7 @@ class DocVisitor(ast.NodeVisitor):
                 self.current_content.append(cleanup(raw))
         self.generic_visit(node)
 
-    def on_new_heading(self) -> None:
+    def _handle_new_heading(self) -> None:
         if self.current_title:
             self.add_to_search_index(self.current_title, self.current_content if self.current_content else 'Overview')
             self.current_content = []
@@ -146,7 +146,7 @@ def generate_for(file: Path, topic: Optional[str] = None) -> None:
     doc_visitor = DocVisitor(topic)
     doc_visitor.visit(tree)
     if doc_visitor.current_title:
-        doc_visitor.on_new_heading()  # to finalize the last heading
+        doc_visitor._handle_new_heading()  # to finalize the last heading
 
 
 documents = []

+ 3 - 3
website/more_documentation/label_documentation.py

@@ -9,13 +9,13 @@ def main_demo() -> None:
 
 def more() -> None:
     @text_demo('Change Appearance Depending on the Content', '''
-        You can overwrite the `on_text_change` method to update other attributes of a label depending on its content. 
+        You can overwrite the `_handle_text_change` method to update other attributes of a label depending on its content. 
         This technique also works for bindings as shown in the example below.
     ''')
     def status():
         class status_label(ui.label):
-            def on_text_change(self, text: str) -> None:
-                super().on_text_change(text)
+            def _handle_text_change(self, text: str) -> None:
+                super()._handle_text_change(text)
                 if text == 'ok':
                     self.classes(replace='text-positive')
                 else: