Skip to content

Instantly share code, notes, and snippets.

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
def simple():
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Stupid log message ' + ' '.join([str(i) for i in range(20)]))
@guyarad
guyarad / lazy_logging.py
Last active November 11, 2016 12:11
Lazy Logging - the below snippet is relevant when you wish to log some debugging information, but that information is relatively costly to generate. Ideally, you'll want to generate that information only when DEBUG level is actually enabled. In other words, only when the message formatting actually occurs.
# IMPLEMENTATION
class LazyLogging(object):
"""
A utility class that wraps a method
"""
def __init__(self, function):
self.function = function
def __str__(self):
@guyarad
guyarad / classic_enum_wrapper_for_sa.py
Created October 5, 2016 20:04
Wrapper for Python classic enum to be used as SQL Alchemy enum type
# DEFINITION
# ==========
class PythonEnumWrapper(sa.Enum):
def __init__(self, cls):
"""
Initializes a new ``PythonEnumWrapper`` to be used as ``sqlalchemy.Enum``
Args:
cls: a classic enumeration type
"""
import wrapt
import functools
def for_all_methods(decorator):
"""
CLASS DECORATOR.
Based on http://stackoverflow.com/a/6307868/916568
When applied to a class, will automatically decorate all public
methods (ones that don't start with an underscore) using the
given ``decorator``.
@guyarad
guyarad / Tidy JSON.py
Last active September 14, 2016 14:23
Text filter intended to be used with TextWrangler application (Mac OSX) in order to reformat (tidy-up) a JSON file.
#!/usr/bin/python
#
# Script was modified from:
# https://steveswinsburg.wordpress.com/2014/09/26/textwrangler-filters-to-tidy-xml-and-tidy-json/
# Modified by Guy Arad, and can be found in:
# https://gist.github.com/guyarad/d80b9d5652a6616e1c3138b6a86310c4
#
# Installation:
# Copy to "~/Library/Application Support/TextWrangler/Text Filters"
#
@guyarad
guyarad / slots_pickling_mixin.py
Last active August 4, 2019 12:39
Enable pickling on Python classes that uses __slots__
class SlotsPicklingMixin(object):
# otherwise, subclasses will still have `__dict__`
__slots__ = ()
def __init__(self):
assert hasattr(self, '__slots__')
def __getstate__(self):
all_slots = itertools.chain.from_iterable(
getattr(t, '__slots__', ()) for t in type(self).__mro__)