Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fmaussion opened this issue Nov 11, 2021 · 3 comments
Closed

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

fmaussion opened this issue Nov 11, 2021 · 3 comments

Comments

@fmaussion
Copy link
Member

fmaussion commented Nov 11, 2021

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?

@max-sixty
Copy link
Collaborator

max-sixty commented Nov 11, 2021

Allowing __format__ to work could be a nice way of letting us having easy ways to represent scalars, while retaining the benefits of always returning an array from xarray methods.

Separate point but FWIW I generally use .item() to get the value out of a scalar array.

@max-sixty
Copy link
Collaborator

@fmaussion how would you envision this working for non-scalar arrays? Would it just raise?

@fmaussion
Copy link
Member Author

fmaussion commented Nov 11, 2021

@fmaussion how would you envision this working for non-scalar arrays? Would it just raise?

Yes, similar to numpy:

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

TypeError: unsupported format string passed to numpy.ndarray.__format__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants