November 2024
Beginner
5 pages
5m
English
When creating instances of a class, you want to return a cached reference to a previous instance created with the same arguments (if any).
The problem being addressed in this Shortcut sometimes arises when you
want to ensure that there is only one instance of a class created for
a set of input arguments. Practical examples include the behavior of
libraries, such as the logging module, that only want to associate a
single logger instance with a given name. For example:
>>>importlogging>>>a=logging.getLogger('foo')>>>b=logging.getLogger('bar')>>>aisbFalse>>>c=logging.getLogger('foo')>>>aiscTrue>>>
To implement this behavior, you should make use of a factory function that’s separate from the class itself. For example:
# The class in questionclassSpam(object):def__init__(self,name):self.name=name# Caching supportimportweakref_spam_cache=weakref.WeakValueDictionary()defget_spam(name):ifnamenotin_spam_cache:s=Spam(name)_spam_cache[name]=selse:s=_spam_cache[name]returns
If you use this implementation, you’ll find that it behaves in the manner shown earlier:
>>>a=get_spam('foo')>>>b=get_spam('bar')>>>aisbFalse>>>c=get_spam('foo')>>>aiscTrue>>>
Writing a special factory ...
Read now
Unlock full access