Created
November 19, 2020 20:00
-
-
Save NimaBavari/33a6a7feff619c2e5cf0079015d83da7 to your computer and use it in GitHub Desktop.
This file contains 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
# simpler case of decorators | |
# memoization with decorator | |
def memoize(func): | |
cache = {} | |
def wrapper(*args, **kwargs): | |
if args not in cache: | |
cache[args] = func(*args, **kwargs) | |
return cache[args] | |
return wrapper | |
@memoize | |
def build_tree(depth): | |
"""Builds a tree of a given depth.""" | |
if depth == 0: | |
return [] | |
return ['leaf %d' % depth, *build_tree(depth - 1)] | |
print(build_tree(5000)) | |
# --------------------------------------------------------- | |
# more complicated case of decorators | |
# call limit | |
import time | |
def once_in(num_secs): | |
def middle(func): | |
last_invoked = 0 | |
def wrapper(*args, **kwargs): | |
nonlocal last_invoked | |
elapsed = time.time() - last_invoked | |
if elapsed < num_secs: | |
raise Exception('Only %f seconds passed' % elapsed) | |
last_invoked = time.time() | |
return func(*args, **kwargs) | |
return wrapper | |
return middle | |
@once_in(40) | |
def log_branch_diagnostics(logfile, branch_no, status): | |
"""Logs diagnostics for the given branch.""" | |
delimiter = '\n' | |
with open(logfile, 'a+') as f: | |
f.write('Branch %d: %s%s' % (branch_no, status, delimiter)) | |
log_branch_diagnostics('lf.log', 32, 'OK') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment