From a3b0e1e76f8e0d7f45f974736a6c238e019c9850 Mon Sep 17 00:00:00 2001 From: flukx Date: Sat, 17 Aug 2024 11:04:37 +0200 Subject: [PATCH] convert to number if possible --- flinventory_gui/search.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/flinventory_gui/search.py b/flinventory_gui/search.py index ff4e671..9bc0830 100644 --- a/flinventory_gui/search.py +++ b/flinventory_gui/search.py @@ -211,6 +211,28 @@ def search_page(parts: list[Part]) -> None: +def try_conversion(value: str, conversions: tuple[Union[Callable[[str], Any], Literal["bool"]]]) -> Any: + """Try to convert value into other values. + + Args: + value: value to be converted + conversions: tuple of conversion functions that raise Exception upon failure + or "bool" which converts the strings "true", "false" + """ + for conversion in conversions: + if conversion == "bool": + if value.lower() == "true": + return True + if value.upper() == "false": + return False + continue + try: + return conversion(value) + except Exception: + pass + return value + + def show_part_changer(ui_element: nicegui.ui.element, part: Part) -> None: """Clear content of ui element and instead display editing fields. @@ -232,7 +254,7 @@ def show_part_changer(ui_element: nicegui.ui.element, part: Part) -> None: if not event.value: del(vars(part.sign)[member]) else: - vars(part.sign)[member] = event.value + vars(part.sign)[member] = try_conversion(event.value, (int, float, "bool")) def save_list_value(event, member): """Split input field at '; ' and save ta part member.""" @@ -270,14 +292,15 @@ def show_part_changer(ui_element: nicegui.ui.element, part: Part) -> None: def save_location(event, schema: location.Schema, location_ui_element) -> None: """Save location input if valid.""" + value = try_conversion(event.value, (int, "bool")) try: - schema.get_subschema(event.value) + schema.get_subschema(value) except location.InvalidLocationSchema as error: print("InvalidLocationSchema: ", error) except location.InvalidLocation: print("Do not save") pass - part.location.set(schema.levelname, event.value) + part.location.set(schema.levelname, value) update_location_element(location_ui_element)