Waht do you think about my repeated_timer class

Chris Angelico rosuav at gmail.com
Wed Feb 2 23:37:01 EST 2022


On Thu, 3 Feb 2022 at 15:28, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>
> On 2022-02-03 at 15:07:22 +1100,
> Chris Angelico <rosuav at gmail.com> wrote:
>
> > On Thu, 3 Feb 2022 at 14:52, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
> > >
> > > 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(...)
> >
> > That's checking something quite different, though. Casting to float
> > will accept anything that can be, well, cast to float, but checking
> > for less than or equal to zero demands that it already be some sort of
> > number. It's debatable which check is more correct, but certainly this
> > is not a simplification of the other code, it's a distinctly different
> > validation.
>
> Okay, "simplified" isn't quite the right word.  Given two examples (with
> known deficiencies) and no actual use cases or specifications, I added a
> third example, which I believed was simpler (and arguably better in one
> or more ways, which I explained), than the others.

Fair :) I'm unsure which is the best check here, or whether it's worth
having any check at all (you could just let the Timer - or
time.sleep() - do the checks).

> > Strange. The text I get in 3.11.0a1 is fine. But in any case, there's
> > always the docs on the web.
> >
> > https://docs.python.org/3/library/threading.html#timer-objects
>
> help(Timer) is built into my REPL (and likely consumed by development
> systems and IDEs everywhere).  No web necessary.

Agreed, and my primary response is that it's fine in my 3.11, so it's
probably something fixable. The web docs are a good fallback though.

> I've slept in enough programming environments to know better than to
> assume anything.  ;-)

Excellent :)

ChrisA


More information about the Python-list mailing list