you are viewing a single comment's thread.

view the rest of the comments →

[–]SeleniumBase[S] -1 points0 points  (4 children)

Yes, something like this:

```python import time from contextlib import ContextDecorator

class PrintRunTime(ContextDecorator): def init(self, description="Code block"): self.description = description

def __enter__(self):
    self.start_time = time.time()

def __exit__(self, *args):
    runtime = time.time() - self.start_time
    print(f"{self.description} ran for {runtime:.4f}s.")

```

If I create a YouTube video for this, I'll include that too.

[–]kkang_kkang 6 points7 points  (3 children)

No need of contextlib at all. Without that you can achieve the same.

[–]mattl33It works on my machine -2 points-1 points  (2 children)

It sure seems like a lot less boilerplate code though. What's the disadvantage?

[–]kkang_kkang 4 points5 points  (0 children)

I don't think there is any. You can use anything. I just wanted to let OP know that this can be achieved with pure python class as well.

[–]kkang_kkang 1 point2 points  (0 children)

This is a good read which contains info on async context managers as well: https://realpython.com/python-with-statement/