1010from collections import defaultdict
1111# Contextlib
1212from contextlib import suppress
13+ # Inspect
14+ from inspect import signature
1315# WeakRef
1416from weakref import WeakSet
1517
@@ -85,17 +87,29 @@ def __init__(cls, classname, bases, attributes):
8587 # New instances of this class will be cached in that dictionary
8688 cls ._cache = {}
8789
90+ # Set whether or not this class is caching its instances by default
91+ try :
92+ cls ._caching = signature (
93+ cls .__init__
94+ ).parameters ['caching' ].default
95+ except KeyError :
96+ cls ._caching = True
97+
8898 # Add the class to the registered classes
8999 _entity_classes .add (cls )
90100
91- def __call__ (cls , index , caching = True ):
101+ def __call__ (cls , index , caching = None ):
92102 """Called when a new instance of this class is requested.
93103
94104 :param int index:
95105 The index of the entity instance requested.
96106 :param bool caching:
97107 Whether to lookup the cache for an existing instance or not.
98108 """
109+ # Get whether or not we should lookup for a cached instance
110+ if caching is None :
111+ caching = cls ._caching
112+
99113 # Let's first lookup for a cached instance
100114 if caching :
101115 obj = cls ._cache .get (index , None )
@@ -112,6 +126,14 @@ def __call__(cls, index, caching=True):
112126 # We are done, let's return the instance
113127 return obj
114128
129+ @property
130+ def caching (cls ):
131+ """Returns whether this class is caching its instances by default.
132+
133+ :rtype: bool
134+ """
135+ return cls ._caching
136+
115137 @property
116138 def cache (cls ):
117139 """Returns the cached instances of this class.
@@ -141,6 +163,10 @@ class also provides dynamic attributes that depend on the entity that is
141163 .. note::
142164 This is not an instance property, so it can only be
143165 accessed through the class itself.
166+
167+ :var caching:
168+ A read-only attribute that returns whether this class is caching its
169+ instances by default.
144170 """
145171
146172 def __init__ (self , index , caching = True ):
0 commit comments