Skip to content

CLN: more consistent error message for construct_from_string wrong type #31387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions pandas/core/arrays/numpy_.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ def construct_from_string(cls, string):
try:
return cls(np.dtype(string))
except TypeError as err:
raise TypeError(
f"Cannot construct a 'PandasDtype' from '{string}'"
) from err
if not isinstance(string, str):
msg = f"'construct_from_string' expects a string, got {type(string)}"
else:
msg = f"Cannot construct a 'PandasDtype' from '{string}'"
raise TypeError(msg) from err

@classmethod
def construct_array_type(cls):
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/arrays/sparse/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ def construct_from_string(cls, string):
-------
SparseDtype
"""
if not isinstance(string, str):
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)
msg = f"Cannot construct a 'SparseDtype' from '{string}'"
if string.startswith("Sparse"):
try:
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,9 @@ def construct_from_string(cls, string: str):
... " "'{string}'")
"""
if not isinstance(string, str):
raise TypeError(f"Expects a string, got {type(string).__name__}")

raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)
# error: Non-overlapping equality check (left operand type: "str", right
# operand type: "Callable[[ExtensionDtype], str]") [comparison-overlap]
assert isinstance(cls.name, str), (cls, type(cls.name))
Expand Down
40 changes: 23 additions & 17 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,9 @@ def construct_from_string(cls, string: str_type) -> "CategoricalDtype":
If a CategoricalDtype cannot be constructed from the input.
"""
if not isinstance(string, str):
raise TypeError(f"Expects a string, got {type(string)}")
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)
if string != cls.name:
raise TypeError(f"Cannot construct a 'CategoricalDtype' from '{string}'")

Expand Down Expand Up @@ -728,22 +730,24 @@ def construct_from_string(cls, string: str_type):
>>> DatetimeTZDtype.construct_from_string('datetime64[ns, UTC]')
datetime64[ns, UTC]
"""
if isinstance(string, str):
msg = f"Cannot construct a 'DatetimeTZDtype' from '{string}'"
match = cls._match.match(string)
if match:
d = match.groupdict()
try:
return cls(unit=d["unit"], tz=d["tz"])
except (KeyError, TypeError, ValueError) as err:
# KeyError if maybe_get_tz tries and fails to get a
# pytz timezone (actually pytz.UnknownTimeZoneError).
# TypeError if we pass a nonsense tz;
# ValueError if we pass a unit other than "ns"
raise TypeError(msg) from err
raise TypeError(msg)
if not isinstance(string, str):
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)

raise TypeError("Cannot construct a 'DatetimeTZDtype'")
msg = f"Cannot construct a 'DatetimeTZDtype' from '{string}'"
match = cls._match.match(string)
if match:
d = match.groupdict()
try:
return cls(unit=d["unit"], tz=d["tz"])
except (KeyError, TypeError, ValueError) as err:
# KeyError if maybe_get_tz tries and fails to get a
# pytz timezone (actually pytz.UnknownTimeZoneError).
# TypeError if we pass a nonsense tz;
# ValueError if we pass a unit other than "ns"
raise TypeError(msg) from err
raise TypeError(msg)

def __str__(self) -> str_type:
return f"datetime64[{self.unit}, {self.tz}]"
Expand Down Expand Up @@ -1075,7 +1079,9 @@ def construct_from_string(cls, string):
if its not possible
"""
if not isinstance(string, str):
raise TypeError(f"a string needs to be passed, got type {type(string)}")
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)

if string.lower() == "interval" or cls._match.search(string) is not None:
return cls(string)
Expand Down
9 changes: 5 additions & 4 deletions pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,12 @@ def test_construct_from_string_raises(self):
with pytest.raises(TypeError, match="notatz"):
DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]")

msg = "^Cannot construct a 'DatetimeTZDtype'"
with pytest.raises(TypeError, match=msg):
msg = "'construct_from_string' expects a string, got <class 'list'>"
with pytest.raises(TypeError, match=re.escape(msg)):
# list instead of string
DatetimeTZDtype.construct_from_string(["datetime64[ns, notatz]"])

msg = "^Cannot construct a 'DatetimeTZDtype'"
with pytest.raises(TypeError, match=msg):
# non-nano unit
DatetimeTZDtype.construct_from_string("datetime64[ps, UTC]")
Expand Down Expand Up @@ -547,9 +548,9 @@ def test_construction_from_string(self):
@pytest.mark.parametrize("string", [0, 3.14, ("a", "b"), None])
def test_construction_from_string_errors(self, string):
# these are invalid entirely
msg = "a string needs to be passed, got type"
msg = f"'construct_from_string' expects a string, got {type(string)}"

with pytest.raises(TypeError, match=msg):
with pytest.raises(TypeError, match=re.escape(msg)):
IntervalDtype.construct_from_string(string)

@pytest.mark.parametrize("string", ["foo", "foo[int64]", "IntervalA"])
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/extension/base/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,10 @@ def test_construct_from_string_another_type_raises(self, dtype):
msg = f"Cannot construct a '{type(dtype).__name__}' from 'another_type'"
with pytest.raises(TypeError, match=msg):
type(dtype).construct_from_string("another_type")

def test_construct_from_string_wrong_type_raises(self, dtype):
with pytest.raises(
TypeError,
match="'construct_from_string' expects a string, got <class 'int'>",
):
type(dtype).construct_from_string(0)