function is_dask_array
Checks whether the provided data object is a Dask array by conditionally importing dask.array and performing an isinstance check.
/tf/active/vicechatdev/patches/util.py
1499 - 1503
simple
Purpose
This function provides a safe way to determine if a data object is a Dask array without requiring dask to be installed. It checks if dask.array is already loaded in sys.modules before attempting to import it, making it suitable for optional dependency scenarios where Dask may or may not be available in the environment.
Source Code
def is_dask_array(data):
da = None
if 'dask.array' in sys.modules:
import dask.array as da
return (da is not None and isinstance(data, da.Array))
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
data |
- | - | positional_or_keyword |
Parameter Details
data: Any Python object to be checked. This can be any data type, but the function specifically checks if it is an instance of dask.array.Array. No constraints on input type.
Return Value
Returns a boolean value. True if the data parameter is a Dask array (dask.array.Array instance) and dask.array is available in sys.modules, False otherwise. Returns False if dask.array is not installed or not yet imported.
Dependencies
sysdask.array
Required Imports
import sys
Conditional/Optional Imports
These imports are only needed under specific conditions:
import dask.array as da
Condition: only imported if 'dask.array' is already present in sys.modules
OptionalUsage Example
import sys
import numpy as np
def is_dask_array(data):
da = None
if 'dask.array' in sys.modules:
import dask.array as da
return (da is not None and isinstance(data, da.Array))
# Example 1: With regular numpy array
np_array = np.array([1, 2, 3])
print(is_dask_array(np_array)) # False
# Example 2: With Dask array (if dask is installed)
try:
import dask.array as da
dask_array = da.from_delayed([1, 2, 3], shape=(3,), dtype=float)
print(is_dask_array(dask_array)) # True
except ImportError:
print("Dask not installed")
# Example 3: With other data types
print(is_dask_array([1, 2, 3])) # False
print(is_dask_array("string")) # False
Best Practices
- This function uses lazy importing to avoid ImportError when dask is not installed, making it safe to use in environments where dask is optional
- The function checks sys.modules first before importing, which is more efficient than using try-except blocks
- Returns False gracefully when dask.array is not available rather than raising an exception
- Should be used when you need to handle both Dask and non-Dask arrays in the same codebase
- Note that this only checks if dask.array has been previously imported; it won't import dask.array for the first time just to check the type
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function is_cupy_array 74.9% similar
-
function is_dataframe 70.7% similar
-
function is_series 68.4% similar
-
function isdatetime 55.7% similar
-
function asarray 50.9% similar