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

feat: Add warning when user tries to access struct series fields with __getitem__ #1082

Merged
merged 19 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions bigframes/core/indexers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import typing
from typing import Tuple, Union
import warnings

import bigframes_vendored.constants as constants
import ibis
Expand All @@ -27,6 +28,7 @@
import bigframes.core.indexes as indexes
import bigframes.core.scalar
import bigframes.dataframe
import bigframes.dtypes
import bigframes.operations as ops
import bigframes.series

Expand Down Expand Up @@ -370,6 +372,7 @@ def _perform_loc_list_join(
# right join based on the old index so that the matching rows from the user's
# original dataframe will be duplicated and reordered appropriately
if isinstance(series_or_dataframe, bigframes.series.Series):
_struct_accessor_check_and_warn(series_or_dataframe, keys_index)
original_name = series_or_dataframe.name
name = series_or_dataframe.name if series_or_dataframe.name is not None else "0"
result = typing.cast(
Expand All @@ -391,6 +394,23 @@ def _perform_loc_list_join(
return result


def _struct_accessor_check_and_warn(
series: bigframes.series.Series, index: indexes.Index
):
if not bigframes.dtypes.is_struct_like(series.dtype):
# No need to check series that do not have struct values
return

if not bigframes.dtypes.is_string_like(index.dtype):
# No need to check indexing with non-string values.
return

if not bigframes.dtypes.is_string_like(series.index.dtype):
warnings.warn(
"Are you trying to access struct fields? If so, please use Series.struct.field(...) method instead."
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do a custom category (defined in bigframes.exceptions) here to make it a bit easier to filter out if needed for some reason?

Also, I recommend setting stacklevel so that the error shows up in user code, not as appearing deep in BigFrames.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have provided a stack level such that the warning call site is now at __getitem__

)


@typing.overload
def _iloc_getitem_series_or_dataframe(
series_or_dataframe: bigframes.series.Series, key
Expand Down
13 changes: 13 additions & 0 deletions tests/system/small/core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
83 changes: 83 additions & 0 deletions tests/system/small/core/test_indexers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pyarrow as pa
import pytest

import bigframes.pandas as bpd


@pytest.mark.parametrize(
("key", "should_warn"),
[
pytest.param(0, False, id="non_string_key_should_not_warn"),
pytest.param("a", True, id="string_key_should_warn"),
],
)
def test_non_string_indexed_series_struct_accessor_warning(session, key, should_warn):
s = bpd.Series(
[
{"project": "pandas", "version": 1},
],
dtype=bpd.ArrowDtype(
pa.struct([("project", pa.string()), ("version", pa.int64())])
),
session=session,
)

if should_warn:
with pytest.warns(UserWarning, match=r"Series\.struct\.field\(.+\)"):
s[key]
else:
s[key]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we have a check that a warning is not raised in this case?

I would prefer two separate tests to make this easier to follow. See go/tott/661

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I separated the tests into two parts: 1 for warning and 1 for no warning. Hopefully this makes it easier to read and understand.



@pytest.mark.parametrize(
"key",
[
pytest.param(0, id="non_string_key"),
pytest.param("a", id="string_key"),
],
)
def test_string_indexed_series_struct_accessor_no_warning(session, key):
s = bpd.Series(
[
{"project": "pandas", "version": 1},
],
dtype=bpd.ArrowDtype(
pa.struct([("project", pa.string()), ("version", pa.int64())])
),
index=["p1"],
session=session,
)

s[key]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this test fail if a warning is raised.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done



@pytest.mark.parametrize(
"key",
[
pytest.param(0, id="non_string_key"),
pytest.param("a", id="string_key"),
],
)
def test_string_indexed_series_non_struct_accessor_no_warning(session, key):
s = bpd.Series(
[1],
dtype=bpd.Int64Dtype,
index=["a"],
session=session,
)

s[key]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this test fail if a warning is raised.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Maybe worth a comment about the filterwarnings above, as it'n not 100% obvious to me.

Alternatively, could we use the solution suggested here, instead?

https://docs.pytest.org/en/stable/how-to/capture-warnings.html#additional-use-cases-of-warnings-in-tests

Suggested change
s[key]
with warnings.catch_warnings():
warnings.simplefilter("error", category=UserWarning)
s[key]

Better yet, have a custom category so we know precisely what warning to fail on.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this approach is simpler. Defined a dedicated warning class instead. I also set a stack level as suggested.