66"""
77from __future__ import annotations
88
9- from collections import abc
109from typing import (
1110 TYPE_CHECKING ,
1211 Any ,
@@ -501,6 +500,16 @@ def sanitize_array(
501500 if dtype is None :
502501 dtype = data .dtype
503502 data = lib .item_from_zerodim (data )
503+ elif isinstance (data , range ):
504+ # GH#16804
505+ data = np .arange (data .start , data .stop , data .step , dtype = "int64" )
506+ copy = False
507+
508+ if not is_list_like (data ):
509+ if index is None :
510+ raise ValueError ("index must be specified when data is not list-like" )
511+ data = construct_1d_arraylike_from_scalar (data , len (index ), dtype )
512+ return data
504513
505514 # GH#846
506515 if isinstance (data , np .ndarray ):
@@ -525,14 +534,16 @@ def sanitize_array(
525534 subarr = subarr .copy ()
526535 return subarr
527536
528- elif isinstance (data , (list , tuple , abc .Set , abc .ValuesView )) and len (data ) > 0 :
529- # TODO: deque, array.array
537+ else :
530538 if isinstance (data , (set , frozenset )):
531539 # Raise only for unordered sets, e.g., not for dict_keys
532540 raise TypeError (f"'{ type (data ).__name__ } ' type is unordered" )
541+
542+ # materialize e.g. generators, convert e.g. tuples, abc.ValueView
543+ # TODO: non-standard array-likes we can convert to ndarray more efficiently?
533544 data = list (data )
534545
535- if dtype is not None :
546+ if dtype is not None or len ( data ) == 0 :
536547 subarr = _try_cast (data , dtype , copy , raise_cast_failure )
537548 else :
538549 subarr = maybe_convert_platform (data )
@@ -541,22 +552,6 @@ def sanitize_array(
541552 # "ExtensionArray")
542553 subarr = maybe_cast_to_datetime (subarr , dtype ) # type: ignore[assignment]
543554
544- elif isinstance (data , range ):
545- # GH#16804
546- arr = np .arange (data .start , data .stop , data .step , dtype = "int64" )
547- subarr = _try_cast (arr , dtype , copy , raise_cast_failure )
548-
549- elif not is_list_like (data ):
550- if index is None :
551- raise ValueError ("index must be specified when data is not list-like" )
552- subarr = construct_1d_arraylike_from_scalar (data , len (index ), dtype )
553-
554- else :
555- # realize e.g. generators
556- # TODO: non-standard array-likes we can convert to ndarray more efficiently?
557- data = list (data )
558- subarr = _try_cast (data , dtype , copy , raise_cast_failure )
559-
560555 subarr = _sanitize_ndim (subarr , data , dtype , index )
561556
562557 if not (
0 commit comments