9
9
import time
10
10
from contextlib import ContextDecorator
11
11
from dataclasses import dataclass , field
12
- from typing import Any , Callable , ClassVar , Optional , Union
12
+ from typing import TYPE_CHECKING , Any , Callable , ClassVar , Optional , Union
13
13
14
14
# Codetiming imports
8000
15
15
from codetiming ._timers import Timers
16
16
17
+ # Special types, Protocol only works for Python >= 3.8
18
+ if TYPE_CHECKING : # pragma: nocover
19
+ # Standard library imports
20
+ from typing import Protocol , TypeVar
17
21
22
+ T = TypeVar ("T" )
23
+
24
+ class FloatArg (Protocol ):
25
+ """Protocol type that allows classes that take one float argument"""
26
+
27
+ def __call__ (self : T , __seconds : float ) -> T :
28
+ """Callable signature"""
29
+ ... # pragma: nocover
30
+
31
+ else :
32
+
33
+ class FloatArg :
34
+ """Dummy runtime class"""
35
+
36
+
37
+ # Timer code
18
38
class TimerError (Exception ):
19
39
"""A custom exception used to report errors in use of Timer class."""
20
40
@@ -24,12 +44,12 @@ class Timer(ContextDecorator):
24
44
"""Time your code using a class, context manager, or decorator."""
25
45
26
46
timers : ClassVar [Timers ] = Timers ()
27
- _start_time : Optional [float ] = field (default = None , init = False , repr = False )
28
47
name : Optional [str ] = None
29
- text : Union [str , Callable [[float ], str ]] = "Elapsed time: {:0.4f} seconds"
30
- initial_text : Union [bool , str ] = False
48
+ text : Union [str , FloatArg , Callable [[float ], str ]] = "Elapsed time: {:0.4f} seconds"
49
+ initial_text : Union [bool , str , FloatArg ] = False
31
50
logger : Optional [Callable [[str ], None ]] = print
32
51
last : float = field (default = math .nan , init = False , repr = False )
52
+ _start_time : Optional [float ] = field (default = None , init = False , repr = False )
33
53
34
54
def start (self ) -> None :
35
55
"""Start a new timer."""
@@ -69,7 +89,7 @@ def stop(self) -> float:
69
89
"minutes" : self .last / 60 ,
70
90
}
71
91
text = self .text .format (self .last , ** attributes )
72
- self .logger (text )
92
+ self .logger (str ( text ) )
73
93
if self .name :
74
94
self .timers .add (self .name , self .last )
75
95
0 commit comments