From bf72d67a8b02fe06ba1efa634cff1c9f6f26a39c Mon Sep 17 00:00:00 2001 From: Filip Ter Date: Sun, 28 Feb 2021 15:07:39 -0800 Subject: ENH: A more helpful error message, when types don't match type of default kwarg --- numpy/lib/function_base.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c6db42ce4..ddc919e4f 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -671,11 +671,23 @@ def select(condlist, choicelist, default=0): raise ValueError("select with an empty condition list is not possible") choicelist = [np.asarray(choice) for choice in choicelist] - choicelist.append(np.asarray(default)) + + try: + intermediate_dtype = np.result_type(*choicelist) + except TypeError as e: + raise TypeError('Choicelist elements do not have a common dtype: {}' + .format(e)) + default_array = np.asarray(default) + choicelist.append(default_array) # need to get the result type before broadcasting for correct scalar # behaviour - dtype = np.result_type(*choicelist) + try: + dtype = np.result_type(intermediate_dtype, default_array) + except TypeError as e: + raise TypeError( + 'Choicelists and default do not have a common dtype: {}' + .format(e)) # Convert conditions to arrays and broadcast conditions and choices # as the shape is needed for the result. Doing it separately optimizes -- cgit v1.2.1 From 0d5eefb1ebd05f3d4aeaf2572460afe9d027aa8f Mon Sep 17 00:00:00 2001 From: Filip Ter Date: Tue, 23 Mar 2021 15:52:45 -0700 Subject: MAINT: Adding exception chaining and switching to fstring --- numpy/lib/function_base.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index ddc919e4f..6921e3df1 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -675,8 +675,8 @@ def select(condlist, choicelist, default=0): try: intermediate_dtype = np.result_type(*choicelist) except TypeError as e: - raise TypeError('Choicelist elements do not have a common dtype: {}' - .format(e)) + msg = f'Choicelist elements do not have a common dtype: {e}' + raise TypeError(msg) from None default_array = np.asarray(default) choicelist.append(default_array) @@ -685,9 +685,8 @@ def select(condlist, choicelist, default=0): try: dtype = np.result_type(intermediate_dtype, default_array) except TypeError as e: - raise TypeError( - 'Choicelists and default do not have a common dtype: {}' - .format(e)) + msg = f'Choicelists and default value do not have a common dtype: {e}' + raise TypeError(msg) from None # Convert conditions to arrays and broadcast conditions and choices # as the shape is needed for the result. Doing it separately optimizes -- cgit v1.2.1