Skip to content

Should str.format() work on xarray scalars? #5976

@fmaussion

Description

@fmaussion

Consider:

da = xr.DataArray([1, 2, 3])
print(f'{da[0]}')
print(f'{da[0]:d}')

Which outputs:

<xarray.DataArray ()>
array(1)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-9cd7dc76455b> in <module>
      1 da = xr.DataArray([1, 2, 3])
      2 print(f'{da[0]}')
----> 3 print(f'{da[0]:d}')

TypeError: unsupported format string passed to DataArray.__format__

And the numpy equivalent:

da = xr.DataArray([1, 2, 3]).data
print(f'{da[0]}')
print(f'{da[0]:d}')
1
1

I always found the xarray scalar output to be a bit unfriendly for beginners. In my classes very often scalars are the last output of a computation, and the fact that we can't format the relatively verbose xarray output without resulting to the .data trick is a bit confusing for students (but I agree this is a detail).

Is there a way to get print(f'{da[0]:d}') to work? Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions