Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions packages/pandas-gbq/pandas_gbq/gbq.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def read_gbq(
col_order=None,
bigquery_client=None,
dry_run: bool = False,
client_options=None,
):
r"""Read data from Google BigQuery to a pandas DataFrame.

Expand Down Expand Up @@ -335,6 +336,7 @@ def read_gbq(
client_id=client_id,
client_secret=client_secret,
bigquery_client=bigquery_client,
client_options=client_options,
)

if _is_query(query_or_table):
Expand Down Expand Up @@ -419,6 +421,7 @@ def to_gbq(
user_agent=None,
rfc9110_delimiter=False,
bigquery_client=None,
client_options=None,
):
"""Write a DataFrame to a Google BigQuery table.

Expand Down Expand Up @@ -621,6 +624,7 @@ def to_gbq(
user_agent=user_agent,
rfc9110_delimiter=rfc9110_delimiter,
bigquery_client=bigquery_client,
client_options=client_options,
)
bqclient = connector.client

Expand Down
39 changes: 22 additions & 17 deletions packages/pandas-gbq/pandas_gbq/gbq_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def __init__(
user_agent=None,
rfc9110_delimiter=False,
bigquery_client=None,
client_options=None,
):
from pandas_gbq import auth

Expand All @@ -69,6 +70,7 @@ def __init__(
self.user_agent = user_agent
self.rfc9110_delimiter = rfc9110_delimiter
self.use_bqstorage_api = use_bqstorage_api
self.client_options = client_options

if bigquery_client is not None:
# If a bq client is already provided, use it to populate auth fields.
Expand Down Expand Up @@ -114,7 +116,11 @@ def __init__(
context.project = self.project_id

self.client = _get_client(
self.user_agent, self.rfc9110_delimiter, self.project_id, self.credentials
self.user_agent,
self.rfc9110_delimiter,
self.project_id,
self.credentials,
client_options=self.client_options,
)

def _start_timer(self):
Expand All @@ -129,21 +135,14 @@ def log_elapsed_seconds(self, prefix="Elapsed", postfix="s.", overlong=6):
logger.info("{} {} {}".format(prefix, sec, postfix))

def get_client(self):
import google.api_core.client_info

bigquery = FEATURES.bigquery_try_import()

user_agent = create_user_agent(
user_agent=self.user_agent, rfc9110_delimiter=self.rfc9110_delimiter
)

client_info = google.api_core.client_info.ClientInfo(
user_agent=user_agent,
)
return bigquery.Client(
project=self.project_id,
credentials=self.credentials,
client_info=client_info,
if getattr(self, "client", None) is not None:
return self.client
return _get_client(
self.user_agent,
self.rfc9110_delimiter,
self.project_id,
self.credentials,
client_options=getattr(self, "client_options", None),
Comment on lines +138 to +145

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using getattr(self, ...) for client and client_options is unnecessary and inconsistent with the direct attribute access used for self.user_agent, self.rfc9110_delimiter, self.project_id, and self.credentials in the same method. Since both self.client and self.client_options are guaranteed to be initialized in __init__, they should be accessed directly.

Suggested change
if getattr(self, "client", None) is not None:
return self.client
return _get_client(
self.user_agent,
self.rfc9110_delimiter,
self.project_id,
self.credentials,
client_options=getattr(self, "client_options", None),
if self.client is not None:
return self.client
return _get_client(
self.user_agent,
self.rfc9110_delimiter,
self.project_id,
self.credentials,
client_options=self.client_options,
)
References
  1. Do not use defensive getattr(self, 'attribute', None) checks for attributes that are guaranteed to be initialized in the class's __init__ method, as it adds unnecessary complexity.

)

@staticmethod
Expand Down Expand Up @@ -302,7 +301,9 @@ def load_data(
self.process_http_error(ex)


def _get_client(user_agent, rfc9110_delimiter, project_id, credentials):
def _get_client(
user_agent, rfc9110_delimiter, project_id, credentials, client_options=None
):
import google.api_core.client_info

bigquery = FEATURES.bigquery_try_import()
Expand All @@ -314,10 +315,14 @@ def _get_client(user_agent, rfc9110_delimiter, project_id, credentials):
client_info = google.api_core.client_info.ClientInfo(
user_agent=user_agent,
)
kwargs = {}
if client_options is not None:
kwargs["client_options"] = client_options
return bigquery.Client(
project=project_id,
credentials=credentials,
client_info=client_info,
**kwargs,
)


Expand Down
124 changes: 124 additions & 0 deletions packages/pandas-gbq/tests/unit/test_universe_domain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright 2026 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.

"""Unit tests for client_options, universe_domain, and bigquery_client reuse."""

from types import MappingProxyType
from unittest import mock

import pandas as pd
import pytest
from google.api_core import client_options as client_options_lib
from google.auth import credentials as auth_credentials

import pandas_gbq
from pandas_gbq import gbq_connector

CUSTOM_UNIVERSE = "apis-tpclp.goog"


def test_gbq_connector_get_client_reuses_supplied_bigquery_client():
supplied_client = mock.Mock(
project="tpc-proj",
_credentials=auth_credentials.AnonymousCredentials(),
)

connector = gbq_connector.GbqConnector(
project_id=None,
bigquery_client=supplied_client,
)

assert connector.client is supplied_client
assert connector.get_client() is supplied_client


@pytest.mark.parametrize(
"opts",
[
pytest.param(
client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE),
id="client_options_instance",
),
pytest.param({"universe_domain": CUSTOM_UNIVERSE}, id="dict"),
pytest.param(
MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}),
id="mapping_proxy",
),
],
)
def test_gbq_connector_forwards_client_options(opts):
fake_creds = auth_credentials.AnonymousCredentials()
with mock.patch.object(
gbq_connector.FEATURES, "bigquery_try_import"
) as mock_bq_import:
mock_bq = mock_bq_import.return_value
connector = gbq_connector.GbqConnector(
project_id="tpc-proj",
credentials=fake_creds,
client_options=opts,
)

mock_bq.Client.assert_called_once()
assert mock_bq.Client.call_args.kwargs["client_options"] is opts
assert connector.get_client() is mock_bq.Client.return_value


def test_gbq_connector_get_client_fallback_forwards_client_options():
opts = client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE)
fake_creds = auth_credentials.AnonymousCredentials()
with mock.patch.object(
gbq_connector.FEATURES, "bigquery_try_import"
) as mock_bq_import:
mock_bq = mock_bq_import.return_value
connector = gbq_connector.GbqConnector(
project_id="tpc-proj",
credentials=fake_creds,
client_options=opts,
)
connector.client = None
connector.get_client()

assert mock_bq.Client.call_count == 2
assert mock_bq.Client.call_args.kwargs["client_options"] is opts


def test_read_gbq_forwards_client_options():
opts = {"universe_domain": CUSTOM_UNIVERSE}
with mock.patch("pandas_gbq.gbq.GbqConnector") as mock_connector_cls:
mock_connector_cls.return_value.run_query.return_value = pd.DataFrame()
pandas_gbq.read_gbq(
"SELECT 1",
project_id="tpc-proj",
client_options=opts,
)

assert mock_connector_cls.call_args.kwargs["client_options"] is opts


def test_to_gbq_forwards_client_options():
opts = client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE)
df = pd.DataFrame({"a": [1]})
with mock.patch("pandas_gbq.gbq.GbqConnector") as mock_connector_cls:
mock_connector = mock_connector_cls.return_value
mock_connector.project_id = "tpc-proj"
mock_connector.client.get_table.side_effect = Exception("stop")
with pytest.raises(Exception, match="stop"):
pandas_gbq.to_gbq(
df,
"ds.tbl",
project_id="tpc-proj",
client_options=opts,
)

assert mock_connector_cls.call_args.kwargs["client_options"] is opts
Loading