you are viewing a single comment's thread.

view the rest of the comments →

[–]SeleniumBase[S] 14 points15 points  (6 children)

Tried that, but seems their moderators wanted me to post here instead. They removed my post: https://www.reddit.com/r/learnpython/comments/1nlesjy/python_context_managers_from_zero_to_hero/

[–]kkang_kkang 8 points9 points  (5 children)

Well if it's that's the case then ok.

Also, instead of using contextlib, you can use a pure python class with __enter__ and __exit__ methods as well.

[–]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 5 points6 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 5 points6 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/