We still have some work to do, since the function is basically doing the same thing in two different places. def repeat_call(func: Callable, interval_ms: int, n_times: int = None) -> None: Depending on the final limit we either check for stopping or never stop. Instead, we can wait for a certain period of time and repeat. If you insert a print statement to your while loop, you can see that it runs a bunch of times without calling the function. In this case it isn't, but there's a much better way of doing it. Now all that's left is defining the function body, which can be arbitrarily complicated. This becomes our starting point when we define a function. What does the user of the function choose, versus us that write it? From your question we can gather that the user chooses a callable, the interval and maybe whether it is called indefinitely or stopped at some point. Let's employ a bit of design to construct our function. The difference between the two classes is that you can't have multiple of the latter because of the class attribute and So even if you made multiple instance of the class, they'd all share that value. If milliseconds - cls.last_milliseconds >= interval: Last_milliseconds = set(cls, interval: int, function: Callable) -> None: Or, even better, you can have a static class if your workflow allows it: class StaticTimer: If milliseconds - self.last_milliseconds >= interval: Strictly speaking about the implementation, if you're not tied to using a function and want to get rid of the usage of global, I'd use a class: from time import timeĭef set(self, interval: int, function: Callable) -> None: You can also remove the parentheses from your condition since - has a higher precedence than >=. If milliseconds - last_milliseconds >= interval: The done variable can also be omitted and added directly to the condition itself: def set_timer(interval: int, function: Callable) -> None: More, round() already returns an int in your case so that can be removed as well. This is subjective and it's just my personal preference but I usually tend to use type annotations only when dealing with function / class definitions and their arguments.įor example, milliseconds: int = int(round(time.time() * 1000)) it's obviously going to be an integer since we can see the cast to int(). Still related to type annotations, I find it kinda hard to read your code with annotations everywhere. You can either use -> None or use nothing at all. For example, for Windows, it will use time.clock() while for Mac and Linux, it will use time.time().First of all, your function doesn't return anything and so you can remove -> bool since it only creates confusion. Internally, timeit() calculates the correct time based on the operating system you're using.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |