Skip to content

Instantly share code, notes, and snippets.

@SPRIME01
Forked from alecklandgraf/good.py
Created October 3, 2016 20:55
Show Gist options
  • Select an option

  • Save SPRIME01/6e6f7a4fd95afdc979cde3c987173553 to your computer and use it in GitHub Desktop.

Select an option

Save SPRIME01/6e6f7a4fd95afdc979cde3c987173553 to your computer and use it in GitHub Desktop.
Python, the good parts
# string format with kwargs
user = {
'first_name': 'John',
'last_name': 'Doe',
'email': 'j.doe@example.com',
}
user_bio = '{first_name} is registered with email: {email}'.format(**user)
# context managers
"""Say you want to write something like this:
with Timer('measure my DB query'):
user_count = User.objects.filter(active=True).count()
And here it would output:
measure my DB query: 0.12
Well, to accomplish this we simply need a python class with __enter__ and __exit__ methods.
"""
import time
class Timer(object):
"""my timer context manager"""
def __init__(self, name):
self.name = name
def __enter__(self):
self.start = time.time()
def __exit__(self, *args):
self.end = time.time()
self.interval = self.end - self.start
print('{name}: {interval}'.format(**self.__dict__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment