1010from collections import defaultdict
1111# Contextlib
1212from contextlib import suppress
13+ # Inspect
14+ from inspect import signature
1315# WeakRef
1416from weakref import WeakSet
1517
@@ -88,17 +90,29 @@ def __init__(cls, classname, bases, attributes):
8890 # New instances of this class will be cached in that dictionary
8991 cls ._cache = {}
9092
93+ # Set whether or not this class is caching its instances by default
94+ try :
95+ cls ._caching = signature (
96+ cls .__init__
97+ ).parameters ['caching' ].default
98+ except KeyError :
99+ cls ._caching = True
100+
91101 # Add the class to the registered classes
92102 _entity_classes .add (cls )
93103
94- def __call__ (cls , index , caching = True ):
104+ def __call__ (cls , index , caching = None ):
95105 """Called when a new instance of this class is requested.
96106
97107 :param int index:
98108 The index of the entity instance requested.
99109 :param bool caching:
100110 Whether to lookup the cache for an existing instance or not.
101111 """
112+ # Get whether or not we should lookup for a cached instance
113+ if caching is None :
114+ caching = cls ._caching
115+
102116 # Let's first lookup for a cached instance
103117 if caching :
104118 try :
@@ -122,6 +136,14 @@ def __call__(cls, index, caching=True):
122136 # We are done, let's return the instance
123137 return obj
124138
139+ @property
140+ def caching (cls ):
141+ """Returns whether this class is caching its instances by default.
142+
143+ :rtype: bool
144+ """
145+ return cls ._caching
146+
125147 @property
126148 def cache (cls ):
127149 """Returns the cached instances of this class.
@@ -162,6 +184,10 @@ class also provides dynamic attributes that depend on the entity that is
162184 .. note::
163185 This is not an instance property, so it can only be
164186 accessed through the class itself.
187+
188+ :var caching:
189+ A read-only attribute that returns whether this class is caching its
190+ instances by default.
165191 """
166192
167193 def __init__ (self , index , caching = True ):
0 commit comments