Last active
July 7, 2022 08:02
-
-
Save alecklandgraf/01882d5ab097a45a766f to your computer and use it in GitHub Desktop.
Python, the good parts
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
# 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) | |
# string format with an object | |
class User(object): | |
"""A lightweight user model""" | |
def __init__(self, first_name, last_name, email): | |
self.first_name = first_name | |
self.last_name = last_name | |
self.email = email | |
user = User('John', 'Doe', 'j.doe@example.com') | |
user_bio = '{user.first_name} is registered with email: {user.email}'.format(user=user) | |
# context managers | |
"""Say you want to time something like this in the shell: | |
In [8]: with Timer('user count'): | |
...: User.objects.count() | |
...: | |
user count: 0.00135397911072 | |
Well, to accomplish this we simply need a python class, Timer, with __enter__ and __exit__ methods. | |
""" | |
import time | |
class Timer(object): | |
"""my timer context manager | |
Mostly borrowed from http://rustyrazorblade.com/2016/02/async-python-and-cassandra-with-gevent/ | |
""" | |
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('{timer.name}: {timer.interval}'.format(timer=self)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment