Skip to content
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

FutureWarning if a table cell is a numpy array #287

Open
alugowski opened this issue Aug 26, 2023 · 1 comment · May be fixed by #288
Open

FutureWarning if a table cell is a numpy array #287

alugowski opened this issue Aug 26, 2023 · 1 comment · May be fixed by #288

Comments

@alugowski
Copy link

import numpy as np
from tabulate import tabulate

data = [[np.ones(1)]]

print(tabulate(data))

Yields this warning from numpy:

/Users/enos/temp/venv/lib/python3.10/site-packages/tabulate/__init__.py:107: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  (len(row) >= 1 and row[0] == SEPARATING_LINE)
-
1
-

The cause is that the line detection function,

def _is_separating_line(row):
    row_type = type(row)
    is_sl = (row_type == list or row_type == str) and (
        (len(row) >= 1 and row[0] == SEPARATING_LINE)
        or (len(row) >= 2 and row[1] == SEPARATING_LINE)
    )
    return is_sl

performs the == operation. This is generally correct, but with numpy (and also other array packages) an == does elementwise comparisons and not object-level. This should still yield the correct answer, just inefficiently and numpy in particular emits that warning.

The fix is simple. Replace the == with is:

        (len(row) >= 1 and row[0] is SEPARATING_LINE)
        or (len(row) >= 2 and row[1] is SEPARATING_LINE)

The is should also be a tiny bit faster, too.

@alugowski
Copy link
Author

Correction, this is now an error in the newest numpy:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The fix is the same.

alugowski added a commit to alugowski/python-tabulate that referenced this issue Aug 28, 2023
This code:
```
import numpy as np
from tabulate import tabulate

data = [[np.ones(1)]]

print(tabulate(data))
```

Throws a `FutureWarning` or a `ValueError` due to the comparison with `SEPARATING_LINE`. 


Fixes astanin#287
@alugowski alugowski linked a pull request Aug 28, 2023 that will close this issue
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

Successfully merging a pull request may close this issue.

1 participant