Python class pooling

I liked JW’s class pooling example at DevLog.nl. Below a rewrite without the global ClassPool and ‘static’ ClassPool.id. Also EAFP in action:

class PooledClass(object):
 'Pools instances by id'
 _pool = {}

 def __new__(cls, id):
  """Creator """
  try:
   return cls._pool[id]
  except KeyError:
   obj = object.__new__(cls)
   cls._pool[id] = obj
   return obj

 def __init__(self, id):
  'Constructor '
  self.id = id

2006-10-09: Changed ‘self’ to ‘cls’ in __new__

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: