diff --git a/set_params_dialog.py b/set_params_dialog.py index de2bac8..59062f3 100644 --- a/set_params_dialog.py +++ b/set_params_dialog.py @@ -1,5 +1,21 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +# BD Fresnel - mechanism parameter dialog +# +# Copyright (C) 2019-2026 Manuel R. Ferdinandus +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . """ set_params_dialog.py ===================== @@ -39,6 +55,7 @@ Usage: previous_mechanism=old_mech) """ +import math import tkinter as tk from tkinter import ttk @@ -102,6 +119,16 @@ class SetParamsDialog(tk.Toplevel): if self._entries and self._entries[0] is not None: self.after(10, self._entries[0].focus_set) + @staticmethod + def _parse(text: str) -> float: + """float(), but rejecting what it accepts and no parameter can + take: "nan", "inf", and overflows such as "1e999". Letting those + through also crashed _format, which calls int() on the value.""" + value = float(text) + if not math.isfinite(value): + raise ValueError(f"{text!r} is not finite") + return value + @staticmethod def _format(value: float) -> str: # MATLAB's num2str-equivalent-enough default formatting. @@ -114,10 +141,10 @@ class SetParamsDialog(tk.Toplevel): if var is None: return try: - value = float(var.get()) + value = self._parse(var.get()) except ValueError: name = MECHANISM_PARAM_SPECS[self.mechanism_name][idx][0] - print(f"set_params_dialog: '{name}' must be a real number; reverting.") + print(f"set_params_dialog: '{name}' must be a finite real number; reverting.") value = self._last_valid[idx] self._last_valid[idx] = value var.set(self._format(value)) @@ -128,7 +155,7 @@ class SetParamsDialog(tk.Toplevel): if var is None: continue try: - values[i] = float(var.get()) + values[i] = self._parse(var.get()) except ValueError: values[i] = self._last_valid[i] self.result = Mechanism(name=self.mechanism_name, param=values)