Skip to content

Commit 5f9d824

Browse files
committed
refactor: deduplicate ipython execution count
1 parent b9c9336 commit 5f9d824

7 files changed

Lines changed: 30 additions & 59 deletions

File tree

packages/bigframes/bigframes/core/utils.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,16 @@ def timedelta_to_micros(
249249
) * 1_000_000 + timedelta.microseconds
250250

251251
raise TypeError(f"Unrecognized input type: {type(timedelta)}")
252+
253+
254+
def get_ipython_execution_count() -> typing.Optional[int]:
255+
"""Returns the current IPython cell execution count if running in a notebook, else None."""
256+
try:
257+
import IPython
258+
259+
ipy = IPython.get_ipython()
260+
if ipy is not None and hasattr(ipy, "execution_count"):
261+
return ipy.execution_count
262+
except (ImportError, NameError):
263+
pass
264+
return None

packages/bigframes/bigframes/display/anywidget.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,9 @@ def __init__(self, dataframe: bigframes.dataframe.DataFrame):
9292

9393
self._dataframe = dataframe
9494

95-
self._cell_execution_count = None
96-
try:
97-
import IPython
95+
from bigframes.core.utils import get_ipython_execution_count
9896

99-
ipy = IPython.get_ipython()
100-
if ipy is not None and hasattr(ipy, "execution_count"):
101-
self._cell_execution_count = ipy.execution_count
102-
except (ImportError, NameError):
103-
pass
97+
self._cell_execution_count = get_ipython_execution_count()
10498

10599
super().__init__()
106100

packages/bigframes/bigframes/session/_io/bigquery/__init__.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -317,14 +317,9 @@ def start_query_with_job(
317317
Starts query job and waits for results.
318318
"""
319319
if cell_execution_count is None:
320-
try:
321-
import IPython
320+
from bigframes.core.utils import get_ipython_execution_count
322321

323-
ipy = IPython.get_ipython()
324-
if ipy is not None and hasattr(ipy, "execution_count"):
325-
cell_execution_count = ipy.execution_count
326-
except (ImportError, NameError):
327-
pass
322+
cell_execution_count = get_ipython_execution_count()
328323

329324
# Note: Ensure no additional labels are added to job_config after this
330325
# point, as `add_and_trim_labels` ensures the label count does not
@@ -382,14 +377,9 @@ def start_query_job_optional(
382377
https://docs.cloud.google.com/bigquery/docs/running-queries#optional-job-creation
383378
"""
384379
if cell_execution_count is None:
385-
try:
386-
import IPython
387-
388-
ipy = IPython.get_ipython()
389-
if ipy is not None and hasattr(ipy, "execution_count"):
390-
cell_execution_count = ipy.execution_count
391-
except (ImportError, NameError):
392-
pass
380+
from bigframes.core.utils import get_ipython_execution_count
381+
382+
cell_execution_count = get_ipython_execution_count()
393383

394384
add_and_trim_labels(job_config, session=session)
395385
try:

packages/bigframes/bigframes/session/execution_spec.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,9 @@ def with_compute_options(self, compute_options: ComputeOptions) -> ExecutionSpec
8181

8282
cell_execution_count = self.cell_execution_count
8383
if cell_execution_count is None:
84-
try:
85-
import IPython
86-
87-
ipy = IPython.get_ipython()
88-
if ipy is not None and hasattr(ipy, "execution_count"):
89-
cell_execution_count = ipy.execution_count
90-
except (ImportError, NameError):
91-
pass
84+
from bigframes.core.utils import get_ipython_execution_count
85+
86+
cell_execution_count = get_ipython_execution_count()
9287

9388
return dataclasses.replace(
9489
self,

packages/bigframes/bigframes/session/metrics.py

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,9 @@ def from_job(
7474
)
7575

7676
if cell_execution_count is None:
77-
try:
78-
import IPython
77+
from bigframes.core.utils import get_ipython_execution_count
7978

80-
ipy = IPython.get_ipython()
81-
if ipy is not None and hasattr(ipy, "execution_count"):
82-
cell_execution_count = ipy.execution_count
83-
except (ImportError, NameError):
84-
pass
79+
cell_execution_count = get_ipython_execution_count()
8580

8681
metadata = cls(
8782
job_id=query_job.job_id,
@@ -147,14 +142,9 @@ def from_row_iterator(
147142
)
148143

149144
if cell_execution_count is None:
150-
try:
151-
import IPython
145+
from bigframes.core.utils import get_ipython_execution_count
152146

153-
ipy = IPython.get_ipython()
154-
if ipy is not None and hasattr(ipy, "execution_count"):
155-
cell_execution_count = ipy.execution_count
156-
except (ImportError, NameError):
157-
pass
147+
cell_execution_count = get_ipython_execution_count()
158148

159149
# fmt: off
160150
return cls(
@@ -328,14 +318,9 @@ def on_event(self, envelope: Any):
328318
self.bytes_processed += bytes_processed
329319

330320
if cell_execution_count is None:
331-
try:
332-
import IPython
333-
334-
ipy = IPython.get_ipython()
335-
if ipy is not None and hasattr(ipy, "execution_count"):
336-
cell_execution_count = ipy.execution_count
337-
except (ImportError, NameError):
338-
pass
321+
from bigframes.core.utils import get_ipython_execution_count
322+
323+
cell_execution_count = get_ipython_execution_count()
339324

340325
metadata = JobMetadata(
341326
job_type="polars",

packages/bigframes/tests/unit/display/test_anywidget.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,18 +185,15 @@ def test_cell_execution_count_propagation(mock_df):
185185
"""Test that the captured cell_execution_count is propagated to to_pandas_batches."""
186186
from bigframes.display.anywidget import TableWidget
187187

188-
# Mock IPython to return a specific execution count
189188
mock_ipy = mock.Mock()
190189
mock_ipy.execution_count = 42
191190

192191
with mock.patch("IPython.get_ipython", return_value=mock_ipy):
193192
with bigframes.option_context("display.render_mode", "anywidget"):
194193
widget = TableWidget(mock_df)
195194

196-
# Verify captured execution count
197195
assert widget._cell_execution_count == 42
198196

199-
# to_pandas_batches should be called with cell_execution_count=42
200197
mock_df.to_pandas_batches.assert_called_with(
201198
page_size=widget.page_size,
202199
cell_execution_count=42,

packages/bigframes/tests/unit/session/test_read_gbq_colab.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,17 +161,14 @@ def test_execution_history_filtering():
161161

162162
session = mocks.create_bigquery_session()
163163

164-
# Add mock jobs to session metrics
165164
job1 = metrics.JobMetadata(job_id="job_1", job_type="query", query="SELECT 1")
166165
job2 = metrics.JobMetadata(job_id="job_2", job_type="query", query="SELECT 2")
167166
session._metrics.jobs.extend([job1, job2])
168167

169-
# Verify filtering by job_ids isolates the target execution
170168
history_job1 = session.execution_history(job_ids=["job_1"]).to_dataframe()
171169
assert len(history_job1) == 1
172170
assert history_job1.iloc[0]["job_id"] == "job_1"
173171

174-
# Verify filtering by events isolates the target execution
175172
event2 = mock.Mock()
176173
event2.job_id = "job_2"
177174
history_job2 = session.execution_history(events=[event2]).to_dataframe()

0 commit comments

Comments
 (0)