Skip to content

Commit

Permalink
feat: adds new function similar to isinstance
Browse files Browse the repository at this point in the history
  • Loading branch information
chalmerlowe committed Jan 9, 2025
1 parent b181341 commit 28bc007
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 6 deletions.
5 changes: 0 additions & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,14 +369,9 @@
"grpc": ("https://grpc.github.io/grpc/python/", None),
"proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None),
"protobuf": ("https://googleapis.dev/python/protobuf/latest/", None),

"dateutil": ("https://dateutil.readthedocs.io/en/latest/", None),

"geopandas": ("https://geopandas.org/", None),

"pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),


}


Expand Down
32 changes: 31 additions & 1 deletion google/cloud/bigquery/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import re
import os
import warnings
from typing import Optional, Union
from typing import Optional, Union, Any, Tuple, Type

from dateutil import relativedelta
from google.cloud._helpers import UTC # type: ignore
Expand Down Expand Up @@ -1004,3 +1004,33 @@ def _verify_job_config_type(job_config, expected_type, param_name="job_config"):
job_config=job_config,
)
)


def _isinstance_or_raise(
value: Any,
dtype: Union[Type, Tuple[Type, ...]],
none_allowed: Optional[bool] = False,
) -> Any:
"""Determine whether a value type matches a given datatype or None.
Args:
value (Any): Value to be checked.
dtype (type): Expected data type or tuple of data types.
none_allowed Optional(bool): whether value is allowed to be None. Default
is False.
Returns:
Any: Returns the input value if the type check is successful.
Raises:
TypeError: If the input value's type does not match the expected data type(s).
"""
if none_allowed and value is None:
return value

if isinstance(value, dtype):
return value

or_none = ""
if none_allowed:
or_none = " (or None)"

msg = f"Pass {value} as a '{dtype}'{or_none}. Got {type(value)}."
raise TypeError(msg)
34 changes: 34 additions & 0 deletions tests/unit/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
from unittest import mock

import google.api_core
from google.cloud.bigquery._helpers import (
_isinstance_or_raise,
)


@pytest.mark.skipif(
Expand Down Expand Up @@ -1661,3 +1664,34 @@ def test_w_env_var(self):
host = self._call_fut()

self.assertEqual(host, HOST)


class Test__isinstance_or_raise:
@pytest.mark.parametrize(
"value,dtype,none_allowed,expected",
[
(None, str, True, None),
("hello world.uri", str, True, "hello world.uri"),
("hello world.uri", str, False, "hello world.uri"),
(None, (str, float), True, None),
("hello world.uri", (str, float), True, "hello world.uri"),
("hello world.uri", (str, float), False, "hello world.uri"),
],
)
def test__valid_isinstance_or_raise(self, value, dtype, none_allowed, expected):
result = _isinstance_or_raise(value, dtype, none_allowed=none_allowed)
assert result == expected

@pytest.mark.parametrize(
"value,dtype,none_allowed,expected",
[
(None, str, False, pytest.raises(TypeError)),
({"key": "value"}, str, True, pytest.raises(TypeError)),
({"key": "value"}, str, False, pytest.raises(TypeError)),
({"key": "value"}, (str, float), True, pytest.raises(TypeError)),
({"key": "value"}, (str, float), False, pytest.raises(TypeError)),
],
)
def test__invalid_isinstance_or_raise(self, value, dtype, none_allowed, expected):
with expected:
_isinstance_or_raise(value, dtype, none_allowed=none_allowed)

0 comments on commit 28bc007

Please sign in to comment.