Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
Old Nov 25th, 2005, 1:51 PM   #1
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Useful code snippets

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]
Arevos is offline   Reply With Quote
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 11:47 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC