8000 Refactor split init by gahjelle · Pull Request #8 · realpython/codetiming · GitHub
[go: up one dir, main page]

Skip to content

Refactor split init #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 3 additions & 63 deletions codetiming/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,85 +4,25 @@

1. As a **class**:

```python
t = Timer(name="class")
t.start()
# Do something
t.stop()
```

2. As a **context manager**:

```python
with Timer(name="context manager"):
# Do something
```

3. As a **decorator**:

```python
@Timer(name="decorator")
def stuff():
# Do something
```
"""

from contextlib import ContextDecorator
from dataclasses import dataclass, field
import time
from typing import Any, Callable, ClassVar, Dict, Optional
# Import Timer for cleaner namespace
from codetiming._timer import Timer, TimerError # noqa

# Versioning is handled by bump2version
__version__ = "0.1.1"


class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""


@dataclass
class Timer(ContextDecorator):
"""Time your code using a class, context manager, or decorator"""

timers: ClassVar[Dict[str, float]] = dict()
name: Optional[str] = None
text: str = "Elapsed time: {:0.4f} seconds"
logger: Optional[Callable[[str], None]] = print
_start_time: Optional[float] = field(default=None, init=False, repr=False)

def __post_init__(self) -> None:
"""Initialization: add timer to dict of timers"""
if self.name:
self.timers.setdefault(self.name, 0)

def start(self) -> None:
"""Start a new timer"""
if self._start_time is not None:
raise TimerError(f"Timer is running. Use .stop() to stop it")

self._start_time = time.perf_counter()

def stop(self) -> float:
"""Stop the timer, and report the elapsed time"""
if self._start_time is None:
raise TimerError(f"Timer is not running. Use .start() to start it")

# Calculate elapsed time
elapsed_time = time.perf_counter() - self._start_time
self._start_time = None

# Report elapsed time
if self.logger:
self.logger(self.text.format(elapsed_time))
if self.name:
self.timers[self.name] += elapsed_time

return elapsed_time

def __enter__(self) -> "Timer":
"""Start a new timer as a context manager"""
self.start()
return self

def __exit__(self, *exc_info: Any) -> None:
"""Stop the context manager timer"""
self.stop()
64 changes: 64 additions & 0 deletions codetiming/_timer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Definition of Timer

See help(codetiming) for quick instructions, and
https://pypi.org/project/codetiming/ for more details.
"""

# Standard library imports
from contextlib import ContextDecorator
from dataclasses import dataclass, field
import time
from typing import Any, Callable, ClassVar, Dict, Optional


class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""


@dataclass
class Timer(ContextDecorator):
"""Time your code using a class, context manager, or decorator"""

timers: ClassVar[Dict[str, float]] = dict()
name: Optional[str] = None
text: str = "Elapsed time: {:0.4f} seconds"
logger: Optional[Callable[[str], None]] = print
_start_time: Optional[float] = field(default=None, init=False, repr=False)

def __post_init__(self) -> None:
"""Initialization: add timer to dict of timers"""
if self.name:
self.timers.setdefault(self.name, 0)

def start(self) -> None:
"""Start a new timer"""
if self._start_time is not None:
raise TimerError(f"Timer is running. Use .stop() to stop it")

self._start_time = time.perf_counter()

def stop(self) -> float:
"""Stop the timer, and report the elapsed time"""
if self._start_time is None:
raise TimerError(f"Timer is not running. Use .start() to start it")

# Calculate elapsed time
elapsed_time = time.perf_counter() - self._start_time
self._start_time = None

# Report elapsed time
if self.logger:
self.logger(self.text.format(elapsed_time))
if self.name:
self.timers[self.name] += elapsed_time

return elapsed_time

def __enter__(self) -> "Timer":
"""Start a new timer as a context manager"""
self.start()
return self

def __exit__(self, *exc_info: Any) -> None:
"""Stop the context manager timer"""
self.stop()
0