10
10
from collections import defaultdict
11
11
# Contextlib
12
12
from contextlib import suppress
13
+ # Inspect
14
+ from inspect import signature
13
15
# WeakRef
14
16
from weakref import WeakSet
15
17
@@ -88,17 +90,29 @@ def __init__(cls, classname, bases, attributes):
88
90
# New instances of this class will be cached in that dictionary
89
91
cls ._cache = {}
90
92
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
+
91
101
# Add the class to the registered classes
92
102
_entity_classes .add (cls )
93
103
94
- def __call__ (cls , index , caching = True ):
104
+ def __call__ (cls , index , caching = None ):
95
105
"""Called when a new instance of this class is requested.
96
106
97
107
:param int index:
98
108
The index of the entity instance requested.
99
109
:param bool caching:
100
110
Whether to lookup the cache for an existing instance or not.
101
111
"""
112
+ # Get whether or not we should lookup for a cached instance
113
+ if caching is None :
114
+ caching = cls ._caching
115
+
102
116
# Let's first lookup for a cached instance
103
117
if caching :
104
118
try :
@@ -122,6 +136,14 @@ def __call__(cls, index, caching=True):
122
136
# We are done, let's return the instance
123
137
return obj
124
138
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
+
125
147
@property
126
148
def cache (cls ):
127
149
"""Returns the cached instances of this class.
@@ -162,6 +184,10 @@ class also provides dynamic attributes that depend on the entity that is
162
184
.. note::
163
185
This is not an instance property, so it can only be
164
186
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.
165
191
"""
166
192
167
193
def __init__ (self , index , caching = True ):
0 commit comments