@@ -108,6 +108,16 @@ class CategoricalDtype(ExtensionDtype):
108
108
kind = 'O'
109
109
str = '|O08'
110
110
base = np .dtype ('O' )
111
+ _cache = {}
112
+
113
+ def __new__ (cls ):
114
+
115
+ try :
116
+ return cls ._cache [cls .name ]
117
+ except KeyError :
118
+ c = object .__new__ (cls )
119
+ cls ._cache [cls .name ] = c
120
+ return c
111
121
112
122
def __hash__ (self ):
113
123
# make myself hashable
@@ -155,38 +165,58 @@ class DatetimeTZDtype(ExtensionDtype):
155
165
base = np .dtype ('M8[ns]' )
156
166
_metadata = ['unit' , 'tz' ]
157
167
_match = re .compile ("(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]" )
168
+ _cache = {}
169
+
170
+ def __new__ (cls , unit = None , tz = None ):
171
+ """ Create a new unit if needed, otherwise return from the cache
158
172
159
- def __init__ (self , unit , tz = None ):
160
- """
161
173
Parameters
162
174
----------
163
175
unit : string unit that this represents, currently must be 'ns'
164
176
tz : string tz that this represents
165
177
"""
166
178
167
179
if isinstance (unit , DatetimeTZDtype ):
168
- self .unit , self .tz = unit .unit , unit .tz
169
- return
180
+ unit , tz = unit .unit , unit .tz
170
181
171
- if tz is None :
182
+ elif unit is None :
183
+ # we are called as an empty constructor
184
+ # generally for pickle compat
185
+ return object .__new__ (cls )
186
+
187
+ elif tz is None :
172
188
173
189
# we were passed a string that we can construct
174
190
try :
175
- m = self ._match .search (unit )
191
+ m = cls ._match .search (unit )
176
192
if m is not None :
177
- self .unit = m .groupdict ()['unit' ]
178
- self .tz = m .groupdict ()['tz' ]
179
- return
193
+ unit = m .groupdict ()['unit' ]
194
+ tz = m .groupdict ()['tz' ]
180
195
except :
181
196
raise ValueError ("could not construct DatetimeTZDtype" )
182
197
198
+ elif isinstance (unit , compat .string_types ):
199
+
200
+ if unit != 'ns' :
201
+ raise ValueError ("DatetimeTZDtype only supports ns units" )
202
+
203
+ unit = unit
204
+ tz = tz
205
+
206
+ if tz is None :
183
207
raise ValueError ("DatetimeTZDtype constructor must have a tz "
184
208
"supplied" )
185
209
186
- if unit != 'ns' :
187
- raise ValueError ("DatetimeTZDtype only supports ns units" )
188
- self .unit = unit
189
- self .tz = tz
210
+ # set/retrieve from cache
211
+ key = (unit , str (tz ))
212
+ try :
213
+ return cls ._cache [key ]
214
+ except KeyError :
215
+ u = object .__new__ (cls )
216
+ u .unit = unit
217
+ u .tz = tz
218
+ cls ._cache [key ] = u
219
+ return u
190
220
191
221
@classmethod
192
222
def construct_from_string (cls , string ):
0 commit comments