Skip to content

Commit ad9f345

Browse files
CLN: refactored code related to issue GH15520
1 parent a358181 commit ad9f345

File tree

3 files changed

+19
-16
lines changed

3 files changed

+19
-16
lines changed

pandas/core/dtypes/common.py

+17-14
Original file line numberDiff line numberDiff line change
@@ -731,23 +731,26 @@ def pandas_dtype(dtype):
731731
except TypeError:
732732
pass
733733

734-
elif dtype == 'object':
735-
return np.dtype(dtype)
736-
737734
try:
738735
return CategoricalDtype.construct_from_string(dtype)
739736
except TypeError:
740737
pass
741738
elif isinstance(dtype, ExtensionDtype):
742739
return dtype
743-
else:
744-
try:
745-
np.dtype(dtype)
746-
except (TypeError, ValueError):
747-
raise
748-
if dtype in [object, np.object_]:
749-
return np.dtype(dtype)
750-
elif np.dtype(dtype).kind == 'O':
751-
raise TypeError('dtype {0} not understood'.format(dtype))
752-
753-
return np.dtype(dtype)
740+
741+
try:
742+
npdtype = np.dtype(dtype)
743+
except (TypeError, ValueError):
744+
raise
745+
746+
# Any invalid dtype (such as pd.Timestamp) should raise an error.
747+
# np.dtype(invalid_type).kind = 0 for such objects. However, this will
748+
# also catch some valid dtypes such as object, np.object_ and 'object'
749+
# which we safeguard against by catching them earlier and returning
750+
# np.dtype(valid_dtype) before this condition is evaluated.
751+
if dtype in [object, np.object_, 'object']:
752+
return npdtype
753+
elif npdtype.kind == 'O':
754+
raise TypeError('dtype {0} not understood'.format(dtype))
755+
756+
return npdtype

pandas/core/generic.py

-1
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,6 @@ def _validate_dtype(self, dtype):
164164
""" validate the passed dtype """
165165

166166
if dtype is not None:
167-
# This would raise an error if an invalid dtype was passed
168167
dtype = pandas_dtype(dtype)
169168

170169
# a compound dtype

pandas/tests/dtypes/test_common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,15 @@
1515
class TestPandasDtype(tm.TestCase):
1616

1717
# Passing invalid dtype, both as a string or object, must raise TypeError
18+
# Per issue GH15520
1819
def test_invalid_dtype_error(self):
1920
msg = 'not understood'
2021
invalid_list = [pd.Timestamp, 'pd.Timestamp']
2122
for dtype in invalid_list:
2223
with tm.assertRaisesRegexp(TypeError, msg):
2324
pandas_dtype(dtype)
2425

25-
valid_list = [object, 'float64', np.object_,
26+
valid_list = [object, 'float64', np.object_, np.dtype('object'),
2627
np.float64, float, np.dtype('float64')]
2728
for dtype in valid_list:
2829
pandas_dtype(dtype)

0 commit comments

Comments
 (0)