Skip to content

Instantly share code, notes, and snippets.

@Eight1911
Last active April 8, 2018 00:12
Show Gist options
  • Save Eight1911/59b08160bbeb8df736bf9ee52161a3b1 to your computer and use it in GitHub Desktop.
Save Eight1911/59b08160bbeb8df736bf9ee52161a3b1 to your computer and use it in GitHub Desktop.
useful Python decorators
#!/usr/bin/env python3
import threading
import functools
import time
import matplotlib.pyplot as plt
from functools import update_wrapper
from time import clock
import threading
import functools
def threadify(func):
"function runs in a new thread."
@functools.wraps(func)
def run(*args, **kwds):
new_thread = threading.Thread(
target = func,
args = args,
kwargs = kwds)
new_thread.start()
return new_thread
return run
# replace with functools.lru_cache
def memoize(f):
"memoize a function"
num_arg = len(inspect.getargspec(f).args)
if num_arg == 1:
class memodict(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = ret = f(key)
return ret
elif num_arg == 0:
a = f()
return lambda: a
else:
class memodict(dict):
__slots__ = ()
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret = self[key] = f(*key)
return ret
return memodict().__getitem__
class timer:
"f.timer(x) to return the amount of time it takes to compute f(x)"
def __init__(self, func):
update_wrapper(self, func)
self.func = func
def __call__(self, *args, **kwds):
return self.func(*args, **kwds)
def withtime(self, *args, **kwds):
func = self.func
begin = clock()
ret = func(*args, **kwds)
end = clock()
return ret, end - begin
def time(self, *args, **kwds):
func = self.func
begin = clock()
ret = func(*args, **kwds)
end = clock()
return end - begin
def plot(self, inputs, show=False):
coordinates = [self.time(i) for i in inputs]
if show:
plt.plot(inputs, coordinates)
plt.show()
return coordinates
class counter:
"""
to count the number of recursions, f.counter(x)
to find the number of times the function has been call
do f.reset()
"""
__slots__ = "f", "begin", "end", "print", "count"
def __init__(self, func):
update_wrapper(self, func)
self.count = 0
self.func = func
def __call__(self, *args, **kwds):
self.count += 1
return self.func(*args, **kwds)
def reset(self):
self.count = 0
def withcounter(self, *args, **kwds):
begin = self.count
resolution = self(*args, **kwds)
end = self.count
return resolution, end - begin
def counter(self, *args, **kwds):
begin = self.count
resolution = self(*args, **kwds)
end = self.count
return end - begin
def logger(message):
"just another message logger"
def funcstring(func, args, kwargs):
return f"{func.__name__}({args}, {kwargs})"
def sublog(func):
@functools.wraps(func)
def main(self, *args, **kwargs):
logstr = funcstring(func, args, kwargs)
self.logs.append((message, logstr))
return func(*args, **kwargs)
return main
return sublog
def setproperty(func):
name = func.__name__
newname = "_" + name
@property
@functools.wraps(func)
def helper(self):
if not hasattr(self, newname):
setattr(self, newname, func(self))
return getattr(self, newname)
return helper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment