How to create a limited set of instanceses of a class

Scott David Daniels scott.daniels at acm.org
Sat Jul 1 14:05:02 EDT 2006


madpython wrote:
> For the pure theory sake and mind expansion i got a question.
> Experimenting with __new__ i found out how to create a singleton.
> class SingleStr(object):
>     def __new__(cls,*args,**kwargs):
>         instance=cls.__dict__.get('instance')
>         if instance:
>             return instance
>         cls.instance=object.__new__(cls,*args,**kwargs)
>         return cls.instance
> 
> What if i need to create no more than 5 (for example) instances of a
> class. I guess that would be not much of a problema but there is a
> complication. If one of the instances is garbagecollected I want to be
> able to spawn another instance....

This should help.  You didn't really say how to pick the result
if there are duplicates, so I just decided for myself.  Read up
on the weakref module, it is your friend in this kind of problem.

     import weakref, random

     class Limited(any_new_style_class):
         _held_instances = weakref.WeakValueDictionary()
         _held_limit = 5
         def __new__(class_, *args, **kwargs):
             if len(class_._held_instances) < class_._held_limit:
                 # You could go over here if threading is an issue
                 instance = super(class_, Limited).__new__(
                                           class_, *args, **kwargs)
                 class_._held_instances[id(instance)] = instance
                 return instance
             return random.choice(class_._held_instances.values())


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list