Skip to content

Commit

Permalink
PERF: Fixed performance regression in Series init (#30571)
Browse files Browse the repository at this point in the history
* PERF: Fixed performance regression in Series init

Closes #30564

* avoid calling
  • Loading branch information
TomAugspurger authored and jbrockmendel committed Dec 31, 2019
1 parent aab7d7c commit ee42275
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
10 changes: 6 additions & 4 deletions pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,12 @@ def is_dtype(cls, dtype) -> bool:
return False
elif isinstance(dtype, cls):
return True
try:
return cls.construct_from_string(dtype) is not None
except TypeError:
return False
if isinstance(dtype, str):
try:
return cls.construct_from_string(dtype) is not None
except TypeError:
return False
return False

@property
def _is_numeric(self) -> bool:
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,11 @@ def construct_from_string(cls, string):
return cls(freq=string)
except ValueError:
pass
raise TypeError(f"Cannot construct a 'PeriodDtype' from '{string}'")
if isinstance(string, str):
msg = f"Cannot construct a 'PeriodDtype' from '{string}'"
else:
msg = f"'construct_from_string' expects a string, got {type(string)}"
raise TypeError(msg)

def __str__(self) -> str_type:
return self.name
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,9 @@ def test_construction_from_string(self):
with pytest.raises(TypeError):
PeriodDtype.construct_from_string("datetime64[ns, US/Eastern]")

with pytest.raises(TypeError, match="list"):
PeriodDtype.construct_from_string([1, 2, 3])

def test_is_dtype(self):
assert PeriodDtype.is_dtype(self.dtype)
assert PeriodDtype.is_dtype("period[D]")
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/extension/base/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ def test_is_dtype_from_self(self, dtype):
result = type(dtype).is_dtype(dtype)
assert result is True

def test_is_dtype_other_input(self, dtype):
assert dtype.is_dtype([1, 2, 3]) is False

def test_is_not_string_type(self, dtype):
return not pd.api.types.is_string_dtype(dtype)

Expand Down

0 comments on commit ee42275

Please sign in to comment.