Skip to content

Commit ee42275

Browse files
TomAugspurgerjbrockmendel
authored andcommitted
PERF: Fixed performance regression in Series init (#30571)
* PERF: Fixed performance regression in Series init Closes #30564 * avoid calling
1 parent aab7d7c commit ee42275

File tree

4 files changed

+17
-5
lines changed

4 files changed

+17
-5
lines changed

pandas/core/dtypes/base.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,12 @@ def is_dtype(cls, dtype) -> bool:
276276
return False
277277
elif isinstance(dtype, cls):
278278
return True
279-
try:
280-
return cls.construct_from_string(dtype) is not None
281-
except TypeError:
282-
return False
279+
if isinstance(dtype, str):
280+
try:
281+
return cls.construct_from_string(dtype) is not None
282+
except TypeError:
283+
return False
284+
return False
283285

284286
@property
285287
def _is_numeric(self) -> bool:

pandas/core/dtypes/dtypes.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,11 @@ def construct_from_string(cls, string):
882882
return cls(freq=string)
883883
except ValueError:
884884
pass
885-
raise TypeError(f"Cannot construct a 'PeriodDtype' from '{string}'")
885+
if isinstance(string, str):
886+
msg = f"Cannot construct a 'PeriodDtype' from '{string}'"
887+
else:
888+
msg = f"'construct_from_string' expects a string, got {type(string)}"
889+
raise TypeError(msg)
886890

887891
def __str__(self) -> str_type:
888892
return self.name

pandas/tests/dtypes/test_dtypes.py

+3
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,9 @@ def test_construction_from_string(self):
408408
with pytest.raises(TypeError):
409409
PeriodDtype.construct_from_string("datetime64[ns, US/Eastern]")
410410

411+
with pytest.raises(TypeError, match="list"):
412+
PeriodDtype.construct_from_string([1, 2, 3])
413+
411414
def test_is_dtype(self):
412415
assert PeriodDtype.is_dtype(self.dtype)
413416
assert PeriodDtype.is_dtype("period[D]")

pandas/tests/extension/base/dtype.py

+3
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ def test_is_dtype_from_self(self, dtype):
3737
result = type(dtype).is_dtype(dtype)
3838
assert result is True
3939

40+
def test_is_dtype_other_input(self, dtype):
41+
assert dtype.is_dtype([1, 2, 3]) is False
42+
4043
def test_is_not_string_type(self, dtype):
4144
return not pd.api.types.is_string_dtype(dtype)
4245

0 commit comments

Comments
 (0)