Waht do you think about my repeated_timer class

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Wed Feb 2 22:31:42 EST 2022


On 2022-02-03 at 12:39:43 +1100,
Cameron Simpson <cs at cskk.id.au> wrote:

> You have:
> 
>     def _check_interval(self, interval):
>         if not type(interval) in [int, float]:
>             raise TypeError('{} is not numeric'.format(interval))
> 
> This check is better written:
> 
>     if not isinstance(interval, (int,float)):
> 
> which handles subclasses of these types (but note that bool subclasses 
> int :-) normally we don't care), or behaviourally:
> 
>     try:
>         interval = float(interval)
>     except ValueError as e:
>         raise TypeError(
>             "cannot convert %s:%r to float: %s"
>             % (type(interval).__name__, interval, e)) from e
> 
> which tries to convert to float and fails if that does not work, which 
> supports classes with a __float__ method (these classes are rare, but 
> decimal.Decimal is one example).

I think this can be simplified for time intervals to the following:

    if interval <= 0:
        raise ValueError(...)

which accepts non-negative real values; throws ValueError for negative
real values; and TypeError for other stuff, including complex numbers
(pathological types notwithstanding).  One thing that doesn't work right
is NaNs, but I'm sure it's not the only code that acts weirdly when
faced with a NaM (curiously, Timer accepts a NaN, but the text I get
from help(Timer) in Python 3.10.2 is, well, broken).

FWIW, I'd find some way to tell users the units (seconds, milliseconds,
fortnights, etc.) instead of making them wade through your code to find
the call to (and possibly the [broken] help text of) Timer.


More information about the Python-list mailing list