A "Best of the Best Practices" (BOBP) guide to developing in Python.
- "Build tools for others that you want to be built for you." - Kenneth Reitz
- "Simplicity is alway better than functionality." - Pieter Hintjens
| # Python 3 | |
| def to_str(bytes_or_str): | |
| if isinstance(bytes_or_str, bytes): | |
| value = bytes_or_str.decode('utf-8') | |
| else: | |
| value = bytes_or_str | |
| return value # Instance of str | |
| def to_bytes(bytes_or_str): |
| from functools import wraps | |
| def trace(func): | |
| @wraps | |
| def wrapper(*args, **kwargs): | |
| result = func(*args, **kwargs) | |
| print('%s(%r, %r) -> %r' % | |
| (func.__name__, args, kwargs, result)) | |
| return result |
| import pandas as pd | |
| import pymysql | |
| from sqlalchemy import create_engine | |
| engine = create_engine('mysql+pymysql://<user>:<password>@<host>[:<port>]/<dbname>') | |
| df = pd.read_sql_query('SELECT * FROM table', engine) | |
| df.head() |
| async def main(): | |
| coroutine1 = do_some_work(1) | |
| coroutine2 = do_some_work(2) | |
| coroutine3 = do_some_work(4) | |
| tasks = [ | |
| asyncio.ensure_future(coroutine1), | |
| asyncio.ensure_future(coroutine2), | |
| asyncio.ensure_future(coroutine3) | |
| ] |
| #!/usr/bin/env python3 | |
| '''Serving dynamic images with Pandas and matplotlib (using flask).''' | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from io import BytesIO |
| """ | |
| A demo of creating a new database via SQL Alchemy. | |
| Under MIT License from sprin (https://gist.github.com/sprin/5846464/) | |
| This module takes the form of a nosetest with three steps: | |
| - Set up the new database. | |
| - Create a table in the new database. | |
| - Teardown the new database. | |
| """ |
| from twisted.enterprise import adbapi | |
| from twisted.python import log | |
| import MySQLdb | |
| class ReconnectingConnectionPool(adbapi.ConnectionPool): | |
| """Reconnecting adbapi connection pool for MySQL. | |
| This class improves on the solution posted at | |
| http://www.gelens.org/2008/09/12/reinitializing-twisted-connectionpool/ | |
| by checking exceptions by error code and only disconnecting the current |