Last active
May 10, 2021 03:01
-
-
Save sanjivyash/2f6a3a6b6fe83aa1b6d2843175c8f449 to your computer and use it in GitHub Desktop.
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
from contextlib import contextmanager | |
from time import time, sleep | |
# decorators | |
def timer(func): | |
def f(*args, **kwargs): | |
before = time() | |
rv = func(*args, **kwargs) | |
after = time() | |
print(f"Time taken = {after- before}") | |
return rv | |
return f | |
@timer | |
def dummy(N): | |
for i in range(N): | |
print("Sleeping for 0.1 secs") | |
sleep(0.1) | |
# generators & decorators | |
def gen_timer(func): | |
def f(*args, **kwargs): | |
before = time() | |
for rv in func(*args, **kwargs): | |
yield rv | |
after = time() | |
print(f"Time taken = {after- before}") | |
return f | |
@gen_timer | |
def generate(N): | |
for i in range(10): | |
# time taken to get data from somewhere | |
sleep(0.1) | |
yield i | |
# context managers | |
def open_database(name): | |
# open the database | |
print("Database opened") | |
# return the file descriptor | |
return 0 | |
def close_database(f): | |
# must call after open_database | |
print("Database closed") | |
@contextmanager | |
def opendb(name): | |
try: | |
assert isinstance(name, str) | |
f = open_database(name) | |
yield f | |
except Exception as e: | |
print(f"[ERROR] {e}") | |
finally: | |
try: | |
close_database(f) | |
except: | |
pass | |
if __name__ == '__main__': | |
# check decorator | |
dummy(10) | |
# check generator | |
for i in generate(10): | |
print(i) | |
# check context manager | |
with opendb("yash") as f: | |
print(f"The returned dummy file descriptor is {f}") | |
with opendb(23) as f: | |
print(f"The returned dummy file descriptor is {f}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment