@@ -172,17 +172,27 @@ def construct_array_type(cls):
172
172
raise NotImplementedError
173
173
174
174
@classmethod
175
- def construct_from_string (cls , string ):
176
- """
177
- Attempt to construct this type from a string.
175
+ def construct_from_string (cls , string : str ):
176
+ r"""
177
+ Construct this type from a string.
178
+
179
+ This is useful mainly for data types that accept parameters.
180
+ For example, a period dtype accepts a frequency parameter that
181
+ can be set as ``period[H]`` (where H means hourly frequency).
182
+
183
+ By default, in the abstract class, just the name of the type is
184
+ expected. But subclasses can overwrite this method to accept
185
+ parameters.
178
186
179
187
Parameters
180
188
----------
181
189
string : str
190
+ The name of the type, for example ``category``.
182
191
183
192
Returns
184
193
-------
185
- self : instance of 'cls'
194
+ ExtensionDtype
195
+ Instance of the dtype.
186
196
187
197
Raises
188
198
------
@@ -191,21 +201,26 @@ def construct_from_string(cls, string):
191
201
192
202
Examples
193
203
--------
194
- If the extension dtype can be constructed without any arguments,
195
- the following may be an adequate implementation.
204
+ For extension dtypes with arguments the following may be an
205
+ adequate implementation.
196
206
197
207
>>> @classmethod
198
- ... def construct_from_string(cls, string)
199
- ... if string == cls.name:
200
- ... return cls()
208
+ ... def construct_from_string(cls, string):
209
+ ... pattern = re.compile(r"^my_type\[(?P<arg_name>.+)\]$")
210
+ ... match = pattern.match(string)
211
+ ... if match:
212
+ ... return cls(**match.groupdict())
201
213
... else:
202
214
... raise TypeError("Cannot construct a '{}' from "
203
- ... "'{}'".format(cls, string))
215
+ ... "'{}'".format(cls.__name__ , string))
204
216
"""
205
- raise AbstractMethodError (cls )
217
+ if string != cls .name :
218
+ raise TypeError ("Cannot construct a '{}' from '{}'" .format (
219
+ cls .__name__ , string ))
220
+ return cls ()
206
221
207
222
@classmethod
208
- def is_dtype (cls , dtype ):
223
+ def is_dtype (cls , dtype ) -> bool :
209
224
"""Check if we match 'dtype'.
210
225
211
226
Parameters
0 commit comments