Here's a few Python code snippets I've used in several programs, that might, possibly, maybe, be useful for others. Does anyone else have any pieces of code that might make life easier for other Python programmers?
def all(s):
"Return true if all elements in an iterable sequence are true."
for x in s:
if not x:
return False
return True
def any(s):
"Return true if any element in an iterable sequence is true."
for x in s:
if x:
return True
return False
class Cache:
"""
Creates a functor that caches the output of a function.
e.g.
image_load = Cache(pygame.image.load)
ball1 = image_load("ball.png")
ball2 = image_load("ball.png") # ball.png only loaded from disk once
"""
def __init__(self, func):
self.store = {}
self.func = func
def __call__(self, key):
try:
return self.store[key]
except KeyError:
self.store[key] = self.func(key)
return self.store[key]