Skip to content

Instantly share code, notes, and snippets.

@aleroddepaz
Last active April 13, 2017 22:17
Show Gist options
  • Save aleroddepaz/5378673 to your computer and use it in GitHub Desktop.
Save aleroddepaz/5378673 to your computer and use it in GitHub Desktop.
Collection of useful functions and patterns for Python
class Singleton(object):
"""
Decorator for the singletton pattern in Python: http://stackoverflow.com/q/31875
Usage::
>>> @Singleton
class MyClassSingleton(object): pass
>>> instance = MyClassSingleton.instance
"""
def __init__(self, decorated):
self.__decorated = decorated
@property
def instance(self):
try:
return self.__instance
except AttributeError:
self.__instance = self.__decorated()
return self.__instance
def __call__(self):
raise TypeError('Singleton must be accessed through instance property')
def __instancecheck__(self, instance):
return isinstance(instance, self.__decorated)
def flatten(x):
"""
Returns a flatten tuple out of a nested structure of lists and tuples::
>>> flatten([1,2,3,(4,5,[6]),[7,8,9]])
(1, 2, 3, 4, 5, 6, 7, 8, 9)
"""
return sum(map(flatten, x), ()) if isinstance(x, (tuple, list)) else (x,)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment