@@ -391,7 +391,10 @@ def test_diff_dataset_repr(self) -> None:
391
391
def test_array_repr (self ) -> None :
392
392
ds = xr .Dataset (coords = {"foo" : [1 , 2 , 3 ], "bar" : [1 , 2 , 3 ]})
393
393
ds [(1 , 2 )] = xr .DataArray ([0 ], dims = "test" )
394
- actual = formatting .array_repr (ds [(1 , 2 )])
394
+ ds_12 = ds [(1 , 2 )]
395
+
396
+ # Test repr function behaves correctly:
397
+ actual = formatting .array_repr (ds_12 )
395
398
expected = dedent (
396
399
"""\
397
400
<xarray.DataArray (1, 2) (test: 1)>
@@ -401,6 +404,14 @@ def test_array_repr(self) -> None:
401
404
402
405
assert actual == expected
403
406
407
+ # Test repr, str prints returns correctly as well:
408
+ assert repr (ds_12 ) == expected
409
+ assert str (ds_12 ) == expected
410
+
411
+ # f-strings (aka format(...)) by default should use the repr:
412
+ actual = f"{ ds_12 } "
413
+ assert actual == expected
414
+
404
415
with xr .set_options (display_expand_data = False ):
405
416
actual = formatting .array_repr (ds [(1 , 2 )])
406
417
expected = dedent (
@@ -422,24 +433,27 @@ def test_array_repr_variable(self) -> None:
422
433
423
434
@requires_dask
424
435
def test_array_scalar_format (self ) -> None :
425
- var = xr .DataArray (0 )
426
- assert var .__format__ ("" ) == "0"
427
- assert var .__format__ ("d" ) == "0"
428
- assert var .__format__ (".2f" ) == "0.00"
436
+ # Test numpy scalars:
437
+ var = xr .DataArray (np .array (0 ))
438
+ assert format (var , "" ) == repr (var )
439
+ assert format (var , "d" ) == "0"
440
+ assert format (var , ".2f" ) == "0.00"
429
441
430
- var = xr .DataArray ([0.1 , 0.2 ])
431
- assert var .__format__ ("" ) == "[0.1 0.2]"
432
- with pytest .raises (TypeError ) as excinfo :
433
- var .__format__ (".2f" )
434
- assert "unsupported format string passed to" in str (excinfo .value )
442
+ # Test dask scalars, not supported however:
443
+ import dask .array as da
435
444
436
- # also check for dask
437
- var = var .chunk (chunks = {"dim_0" : 1 })
438
- assert var .__format__ ("" ) == "[0.1 0.2]"
445
+ var = xr .DataArray (da .array (0 ))
446
+ assert format (var , "" ) == repr (var )
439
447
with pytest .raises (TypeError ) as excinfo :
440
- var . __format__ ( ".2f" )
448
+ format ( var , ".2f" )
441
449
assert "unsupported format string passed to" in str (excinfo .value )
442
450
451
+ # Test numpy arrays raises:
452
+ var = xr .DataArray ([0.1 , 0.2 ])
453
+ with pytest .raises (NotImplementedError ) as excinfo : # type: ignore
454
+ format (var , ".2f" )
455
+ assert "Using format_spec is only supported" in str (excinfo .value )
456
+
443
457
444
458
def test_inline_variable_array_repr_custom_repr () -> None :
445
459
class CustomArray :
0 commit comments