Created
August 8, 2024 20:02
-
-
Save diogobaeder/dbb31e4b99ca9738267d0631cde5106d to your computer and use it in GitHub Desktop.
contextmanager as with block and as decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import time | |
from contextlib import contextmanager | |
@contextmanager | |
def timing(): | |
start = time.time() | |
yield | |
elapsed = time.time() - start | |
print("Took", elapsed, "seconds to run") | |
@timing() | |
def foo(): | |
print("foo will sleep") | |
time.sleep(0.2) | |
def bar(): | |
with timing(): | |
print("bar will sleep") | |
time.sleep(0.3) | |
if __name__ == '__main__': | |
foo() | |
bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment