convert to number if possible
This commit is contained in:
parent
2fe607cd4c
commit
a3b0e1e76f
1 changed files with 26 additions and 3 deletions
|
@ -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)
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue