Frequently Copied and Pasted
source link: https://bbengfort.github.io/2016/01/frequently-copy-pasted/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Frequently Copied and Pasted
I have a bit of catch up to do — and I think that this notepad and development journal is the perfect resource to do it. You see, I am constantly copy and pasting code from other projects into the current project that I’m working on. Usually this takes the form of a problem that I had solved previously that has a similar domain to a new problem, but requires a slight amount of tweaking. Other times I am just doing the same task over and over again.
“But Ben, if you’re repeating yourself, shouldn’t you just make an open source module, require it as a dependency and import it?”
Says you, whose voice sounds strangely like that of @looselycoupled. Well of course I should, but the problem is that takes time — how much of that do you think I have? I’ve tried to get a
benlib going in the past; but upkeep is tough. And anyway I have done that. The prime example is confire, because we kept using the same YAML configuration code over and over again.
In fact there are two massive pieces of code that need to be made into a library, if only for our own sanity:
console utilities: we like to wrap
argparseinto a Django-like command program. Then all we have to do is write
Commandsubclasses and they’re automatically added to our application. This needs to be a library ASAP. While we’re at it, we may as well stick our
WrappedLoggerutility in as well.
sql query (ormbad): ORMs are such a pain, especially if you’re good at SQL (we are). We constantly write this
Queryclass to wrap our SQL and load them from disk, etc. In fairness, we actually have started the dependency: ormbad, but we need to finish it.
However, there is also a whole host of stuff that we use in our utilities, like the famous
Timer class that we got from (somewhere?) and use all the time.
from functools import wraps from dateutil.relativedelta import relativedelta
def humanizedelta(*args, **kwargs): """ Wrapper around dateutil.relativedelta (same construtor args) and returns a humanized string representing the delta in a meaningful way. """ delta = relativedelta(*args, **kwargs) attrs = ('years', 'months', 'days', 'hours', 'minutes', 'seconds') parts = [ '%d %s' % (getattr(delta, attr), getattr(delta, attr) > 1 and attr or attr[:-1]) for attr in attrs if getattr(delta, attr) ]
return " ".join(parts)
class Timer(object): """ A context object timer. Usage: >>> with Timer() as timer: ... do_something() >>> print timer.interval """
def __init__(self, wall_clock=True): """ If wall_clock is True then use time.time() to get the number of actually elapsed seconds. If wall_clock is False, use time.clock to get the process time instead. """ self.wall_clock = wall_clock self.time = time.time if wall_clock else time.clock
def __enter__(self): self.start = self.time() return self
def __exit__(self, type, value, tb): self.finish = self.time() self.interval = self.finish - self.start
def __str__(self): return humanizedelta(seconds=self.interval)
def timeit(func, wall_clock=True): """ Times a function; returns a Timer along with the result. """ @wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ with Timer(wall_clock) as timer: result = func(*args, **kwargs)
return result, timer return timer_wrapper
But you know, hunting for Gists is hard, hunting for code in other repositories is hard. So you know what? I’m just going to put it all here. Quick and dirty in the hopes that I’ll have a one stop shop for copy and paste. Plus embedding those Gists is very, very handy.
Aggregate valuable and interesting links.
Joyk means Joy of geeK