@@ -1813,7 +1813,7 @@ def _create_generic_cf_array_var(
18131813 if cube is not None and data is not None and cube .shape != data .shape :
18141814 compression_kwargs = {}
18151815
1816- if np .issubdtype (data .dtype , np .str_ ):
1816+ if not is_dataless and np .issubdtype (data .dtype , np .str_ ):
18171817 # Deal with string-type variables.
18181818 # Typically CF label variables, but also possibly ancil-vars ?
18191819
@@ -1898,8 +1898,13 @@ def _create_generic_cf_array_var(
18981898 else :
18991899 # A normal (numeric) variable.
19001900 # ensure a valid datatype for the file format.
1901- element_type = type (element ).__name__
1902- data = self ._ensure_valid_dtype (data , element_type , element )
1901+ if is_dataless :
1902+ dtype = self ._DATALESS_DTYPE
1903+ fill_value = self ._DATALESS_FILLVALUE
1904+ else :
1905+ element_type = type (element ).__name__
1906+ data = self ._ensure_valid_dtype (data , element_type , element )
1907+ dtype = data .dtype .newbyteorder ("=" )
19031908
19041909 # Check if this is a dim-coord.
19051910 is_dimcoord = cube is not None and element in cube .dim_coords
@@ -1913,7 +1918,7 @@ def _create_generic_cf_array_var(
19131918 # Create the CF-netCDF variable.
19141919 cf_var = self ._dataset .createVariable (
19151920 cf_name ,
1916- data . dtype . newbyteorder ( "=" ) ,
1921+ dtype ,
19171922 element_dims ,
19181923 fill_value = fill_value ,
19191924 ** compression_kwargs ,
@@ -2365,19 +2370,12 @@ def _create_cf_data_variable(
23652370 # be removed.
23662371 # Get the values in a form which is valid for the file format.
23672372 is_dataless = cube .is_dataless ()
2368- if is_dataless :
2369- data = None
2370- else :
2371- data = self ._ensure_valid_dtype (cube .core_data (), "cube" , cube )
23722373
2373- if is_dataless :
2374- # The variable must have *some* dtype, and it must be maskable
2375- dtype = self ._DATALESS_DTYPE
2376- fill_value = self ._DATALESS_FILLVALUE
2377- elif not packing :
2378- dtype = data .dtype .newbyteorder ("=" )
2379- else :
2380- if isinstance (packing , dict ):
2374+ if not is_dataless :
2375+ data = self ._ensure_valid_dtype (cube .core_data (), "cube" , cube )
2376+ if not packing :
2377+ dtype = data .dtype .newbyteorder ("=" )
2378+ elif isinstance (packing , dict ):
23812379 if "dtype" not in packing :
23822380 msg = "The dtype attribute is required for packing."
23832381 raise ValueError (msg )
0 commit comments