Last active
April 13, 2017 22:17
-
-
Save aleroddepaz/5378673 to your computer and use it in GitHub Desktop.
Collection of useful functions and patterns for Python
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
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