Skip to content

Commit 45b812f

Browse files
committed
Finalize type hints in googleads/*.py files
Change-Id: I861a4d620d0214946c17b5f1759cf65053dc1cd5
1 parent 4bef0f7 commit 45b812f

File tree

5 files changed

+64
-65
lines changed

5 files changed

+64
-65
lines changed

google/ads/googleads/client.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
)
3232

3333
from types import ModuleType
34-
from typing import Any, Dict, Tuple, Union
34+
from typing import Any, Dict, List, Tuple, Union
3535

3636
_logger = logging.getLogger(__name__)
3737

@@ -74,7 +74,7 @@ def __init__(self, client: "GoogleAdsClient") -> None:
7474
"""
7575
self._client: "GoogleAdsClient" = client
7676
self._version: str = client.version or _DEFAULT_VERSION
77-
self._enums: Tuple[str] | None = None
77+
self._enums: Union[Tuple[str], None] = None
7878
self._use_proto_plus: bool = client.use_proto_plus
7979

8080
def __dir__(self) -> Tuple[str]:
@@ -107,7 +107,7 @@ def __getattr__(self, name: str) -> Union[ProtoPlusMessageType, ProtobufMessageT
107107
try:
108108
enum_class = self._client.get_type(name)
109109

110-
if self._use_proto_plus == True:
110+
if self._use_proto_plus:
111111
for attr in dir(enum_class):
112112
attr_val = getattr(enum_class, attr)
113113
if isinstance(attr_val, ProtoEnumMeta):
@@ -414,28 +414,28 @@ def get_service(
414414
options=_GRPC_CHANNEL_OPTIONS,
415415
)
416416

417-
interceptors: List[grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor] = interceptors + [
418-
MetadataInterceptor( # type: ignore[no-untyped-call]
417+
interceptors: List[Union[grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor]] = interceptors + [
418+
MetadataInterceptor(
419419
self.developer_token,
420420
self.login_customer_id,
421421
self.linked_customer_id,
422422
self.use_cloud_org_for_api_access,
423423
),
424-
LoggingInterceptor(_logger, version, endpoint), # type: ignore[no-untyped-call]
425-
ExceptionInterceptor( # type: ignore[no-untyped-call]
424+
LoggingInterceptor(_logger, version, endpoint),
425+
ExceptionInterceptor(
426426
version, use_proto_plus=self.use_proto_plus
427427
),
428428
]
429429

430-
channel = grpc.intercept_channel(channel, *interceptors) # type: ignore[no-untyped-call]
430+
channel: grpc.Channel = grpc.intercept_channel(channel, *interceptors)
431431

432-
service_transport = service_transport_class(
432+
service_transport: Any = service_transport_class(
433433
channel=channel, client_info=_CLIENT_INFO
434434
)
435435

436436
return service_client_class(transport=service_transport)
437437

438-
def get_type(self, name: str, version: str = _DEFAULT_VERSION): # type: ignore[no-untyped-def]
438+
def get_type(self, name: str, version: str = _DEFAULT_VERSION) -> Union[ProtoPlusMessageType, ProtobufMessageType]:
439439
"""Returns the specified common, enum, error, or resource type.
440440
441441
Args:
@@ -469,19 +469,19 @@ def get_type(self, name: str, version: str = _DEFAULT_VERSION): # type: ignore[
469469

470470
# If version is specified when the instance is created,
471471
# override any version specified as an argument.
472-
version = self.version if self.version else version
473-
type_classes = self._get_api_services_by_version(version)
472+
version: str = self.version if self.version else version
473+
type_classes: ModuleType = self._get_api_services_by_version(version)
474474

475475
for type_name in _MESSAGE_TYPES:
476476
if type_name == "services":
477-
path = f"{type_name}.types.{name}"
477+
path: str = f"{type_name}.types.{name}"
478478
else:
479-
path = f"{type_name}.{name}"
479+
path: str = f"{type_name}.{name}"
480480

481481
try:
482-
message_class = util.get_nested_attr(type_classes, path) # type: ignore[no-untyped-call]
482+
message_class: Union[ProtoPlusMessageType, ProtobufMessageType] = util.get_nested_attr(type_classes, path) # type: ignore[no-untyped-call]
483483

484-
if self.use_proto_plus == True:
484+
if self.use_proto_plus:
485485
return message_class()
486486
else:
487487
return util.convert_proto_plus_to_protobuf(message_class()) # type: ignore[no-untyped-call]

google/ads/googleads/config.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import logging.config
1919
import os
2020
import re
21+
from typing import Any, Callable, List, Tuple, TypeVar, Union
2122
import yaml
2223

2324

@@ -45,7 +46,6 @@
4546
"path_to_private_key_file",
4647
"delegated_account",
4748
)
48-
from typing import Any, Callable, TypeVar
4949

5050
_KEYS_ENV_VARIABLES_MAP: dict[str, str] = {
5151
key: _ENV_PREFIX + key.upper()
@@ -71,12 +71,12 @@ def _config_validation_decorator(func: F) -> F:
7171
"""
7272

7373
@functools.wraps(func)
74-
def validation_wrapper(*args: Any, **kwargs: Any) -> Any:
74+
def validation_wrapper(*args: Any, **kwargs: Any) -> dict[str, Any]:
7575
config_dict: dict[str, Any] = func(*args, **kwargs)
7676
validate_dict(config_dict)
7777
return config_dict
7878

79-
return validation_wrapper # type: ignore[return-value]
79+
return validation_wrapper
8080

8181

8282
def _config_parser_decorator(func: F) -> F:
@@ -94,17 +94,17 @@ def parser_wrapper(*args: Any, **kwargs: Any) -> Any:
9494
parsed_config: dict[str, Any] = convert_login_customer_id_to_str(
9595
config_dict
9696
)
97-
parsed_config = convert_linked_customer_id_to_str(parsed_config)
97+
parsed_config: dict[str, Any] = convert_linked_customer_id_to_str(parsed_config)
9898

99-
config_keys = parsed_config.keys()
99+
config_keys: List[str] = parsed_config.keys()
100100

101101
if "logging" in config_keys:
102-
logging_config = parsed_config["logging"]
102+
logging_config: dict[str, Any] = parsed_config["logging"]
103103
# If the logging config is a dict then it is already in the format
104104
# that needs to be returned by this method.
105105
if type(logging_config) is not dict:
106106
try:
107-
parsed_config["logging"] = json.loads(logging_config)
107+
parsed_config["logging"]: dict[str, Any] = json.loads(logging_config)
108108
# The logger is configured here in case deprecation warnings
109109
# need to be logged further down in this method. The logger
110110
# is otherwise configured by the GoogleAdsClient class.
@@ -156,12 +156,12 @@ def parser_wrapper(*args: Any, **kwargs: Any) -> Any:
156156
# variable we need to manually change it to the bool False because
157157
# the string "False" is truthy and can easily be incorrectly
158158
# converted to the boolean True.
159-
value = parsed_config.get("use_proto_plus", False)
160-
parsed_config["use_proto_plus"] = disambiguate_string_bool(value)
159+
value: Union[str, bool] = parsed_config.get("use_proto_plus", False)
160+
parsed_config["use_proto_plus"]: bool = disambiguate_string_bool(value)
161161

162162
return parsed_config
163163

164-
return parser_wrapper # type: ignore[return-value]
164+
return parser_wrapper
165165

166166

167167
def validate_dict(config_data: dict[str, Any]) -> None:
@@ -178,7 +178,7 @@ def validate_dict(config_data: dict[str, Any]) -> None:
178178
Raises:
179179
ValueError: If the dict does not contain all required config keys.
180180
"""
181-
if not "use_proto_plus" in config_data.keys():
181+
if "use_proto_plus" not in config_data.keys():
182182
raise ValueError(
183183
"The client library configuration is missing the required "
184184
'"use_proto_plus" key. Please set this option to either "True" '
@@ -200,7 +200,7 @@ def validate_dict(config_data: dict[str, Any]) -> None:
200200
validate_linked_customer_id(str(config_data["linked_customer_id"]))
201201

202202

203-
def _validate_customer_id(customer_id: str | None, id_type: str) -> None:
203+
def _validate_customer_id(customer_id: Union[str, None], id_type: str) -> None:
204204
"""Validates a customer ID.
205205
206206
Args:
@@ -214,15 +214,15 @@ def _validate_customer_id(customer_id: str | None, id_type: str) -> None:
214214
"""
215215
if customer_id is not None:
216216
# Checks that the string is comprised only of 10 digits.
217-
pattern = re.compile(r"^\d{10}", re.ASCII)
217+
pattern: re.Pattern = re.compile(r"^\d{10}", re.ASCII)
218218
if not pattern.fullmatch(customer_id):
219219
raise ValueError(
220220
f"The specified {id_type} customer ID is invalid. It must be a "
221221
"ten digit number represented as a string, i.e. '1234567890'"
222222
)
223223

224224

225-
def validate_login_customer_id(login_customer_id: str | None) -> None:
225+
def validate_login_customer_id(login_customer_id: Union[str, None]) -> None:
226226
"""Validates a login customer ID.
227227
Args:
228228
login_customer_id: a str from config indicating a login customer ID.
@@ -233,7 +233,7 @@ def validate_login_customer_id(login_customer_id: str | None) -> None:
233233
_validate_customer_id(login_customer_id, "login")
234234

235235

236-
def validate_linked_customer_id(linked_customer_id: str | None) -> None:
236+
def validate_linked_customer_id(linked_customer_id: Union[str, None]) -> None:
237237
"""Validates a linked customer ID.
238238
Args:
239239
linked_customer_id: a str from config indicating a linked customer ID.
@@ -246,7 +246,7 @@ def validate_linked_customer_id(linked_customer_id: str | None) -> None:
246246

247247
@_config_validation_decorator
248248
@_config_parser_decorator
249-
def load_from_yaml_file(path: str | None = None) -> dict[str, Any]:
249+
def load_from_yaml_file(path: Union[str, None] = None) -> dict[str, Any]:
250250
"""Loads configuration data from a YAML file and returns it as a dict.
251251
252252
Args:
@@ -264,20 +264,20 @@ def load_from_yaml_file(path: str | None = None) -> dict[str, Any]:
264264
# If no path is specified then we check for the environment variable
265265
# that may define the path. If that is not defined then we use the
266266
# default path.
267-
path_from_env_var = os.environ.get(
267+
path_from_env_var: str = os.environ.get(
268268
_ENV_PREFIX + _CONFIG_FILE_PATH_KEY[0].upper()
269269
)
270-
path = (
270+
path: Tuple[str] = (
271271
path_from_env_var
272272
if path_from_env_var
273273
else os.path.join(os.path.expanduser("~"), "google-ads.yaml")
274274
)
275275

276276
if not os.path.isabs(path):
277-
path = os.path.expanduser(path)
277+
path: str = os.path.expanduser(path)
278278

279279
with open(path, "rb") as handle:
280-
yaml_doc = handle.read()
280+
yaml_doc: bytes = handle.read()
281281

282282
return parse_yaml_document_to_dict(yaml_doc)
283283

@@ -308,7 +308,7 @@ def load_from_dict(config_dict: dict[str, Any]) -> dict[str, Any]:
308308

309309
@_config_validation_decorator
310310
@_config_parser_decorator
311-
def parse_yaml_document_to_dict(yaml_doc: str | bytes) -> dict[str, Any]:
311+
def parse_yaml_document_to_dict(yaml_doc: Union[str, bytes]) -> dict[str, Any]:
312312
"""Parses a YAML document to a dict.
313313
314314
Args:
@@ -382,10 +382,10 @@ def convert_login_customer_id_to_str(
382382
Returns:
383383
The same config dict object with a mutated login_customer_id attr.
384384
"""
385-
login_customer_id: Any = config_data.get("login_customer_id")
385+
login_customer_id: str = config_data.get("login_customer_id")
386386

387387
if login_customer_id:
388-
config_data["login_customer_id"] = str(login_customer_id)
388+
config_data["login_customer_id"]: str = str(login_customer_id)
389389

390390
return config_data
391391

@@ -405,15 +405,15 @@ def convert_linked_customer_id_to_str(
405405
Returns:
406406
The same config dict object with a mutated linked_customer_id attr.
407407
"""
408-
linked_customer_id: Any = config_data.get("linked_customer_id")
408+
linked_customer_id: str = config_data.get("linked_customer_id")
409409

410410
if linked_customer_id:
411-
config_data["linked_customer_id"] = str(linked_customer_id)
411+
config_data["linked_customer_id"]: str = str(linked_customer_id)
412412

413413
return config_data
414414

415415

416-
def disambiguate_string_bool(value: str | bool) -> bool:
416+
def disambiguate_string_bool(value: Union[str, bool]) -> bool:
417417
"""Converts a stringified boolean to its bool representation.
418418
419419
Args:

google/ads/googleads/errors.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@
1313
# limitations under the License.
1414
"""Errors used by the Google Ads API library."""
1515

16-
17-
from typing import Any
1816
import grpc
17+
from proto import Message as ProtobufMessageType
1918

2019

2120
class GoogleAdsException(Exception):
@@ -25,7 +24,7 @@ def __init__(
2524
self,
2625
error: grpc.RpcError,
2726
call: grpc.Call,
28-
failure: Any, # Replace Any with GoogleAdsFailure when available
27+
failure: ProtobufMessageType,
2928
request_id: str,
3029
) -> None:
3130
"""Initializer.
@@ -39,5 +38,5 @@ def __init__(
3938
"""
4039
self.error: grpc.RpcError = error
4140
self.call: grpc.Call = call
42-
self.failure: Any = failure # Replace Any with GoogleAdsFailure
41+
self.failure: ProtobufMessageType = failure
4342
self.request_id: str = request_id

google/ads/googleads/oauth2.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
from google.ads.googleads import config
2525

26-
from typing import Any, Callable, TypeVar
26+
from typing import Any, Callable, TypeVar, Union
2727

2828
_SERVICE_ACCOUNT_SCOPES: list[str] = [
2929
"https://www.googleapis.com/auth/adwords"
@@ -42,27 +42,27 @@ def _initialize_credentials_decorator(func: F) -> F:
4242

4343
@functools.wraps(func)
4444
def initialize_credentials_wrapper(*args: Any, **kwargs: Any) -> Any:
45-
credentials = func(*args, **kwargs)
45+
credentials: Union[InstalledAppCredentials, ServiceAccountCreds] = func(*args, **kwargs)
4646
# If the configs contain an http_proxy, refresh credentials through the
4747
# proxy URI
48-
proxy: str | None = kwargs.get("http_proxy")
48+
proxy: Union[str, None] = kwargs.get("http_proxy")
4949
if proxy:
50-
session = Session()
50+
session: Session = Session()
5151
session.proxies.update({"http": proxy, "https": proxy})
5252
credentials.refresh(Request(session=session))
5353
else:
54-
credentials.refresh(Request()) # type: ignore[no-untyped-call]
54+
credentials.refresh(Request())
5555
return credentials
5656

57-
return initialize_credentials_wrapper # type: ignore[return-value]
57+
return initialize_credentials_wrapper
5858

5959

6060
@_initialize_credentials_decorator
6161
def get_installed_app_credentials(
6262
client_id: str,
6363
client_secret: str,
6464
refresh_token: str,
65-
http_proxy: str | None = None,
65+
http_proxy: Union[str, None] = None,
6666
token_uri: str = _DEFAULT_TOKEN_URI,
6767
) -> InstalledAppCredentials:
6868
"""Creates and returns an instance of oauth2.credentials.Credentials.
@@ -90,7 +90,7 @@ def get_installed_app_credentials(
9090
def get_service_account_credentials(
9191
json_key_file_path: str,
9292
subject: str,
93-
http_proxy: str | None = None,
93+
http_proxy: Union[str, None] = None,
9494
scopes: list[str] = _SERVICE_ACCOUNT_SCOPES,
9595
) -> ServiceAccountCreds:
9696
"""Creates and returns an instance of oauth2.service_account.Credentials.
@@ -111,7 +111,7 @@ def get_service_account_credentials(
111111

112112
def get_credentials(
113113
config_data: dict[str, Any]
114-
) -> InstalledAppCredentials | ServiceAccountCreds:
114+
) -> Union[InstalledAppCredentials, ServiceAccountCreds]:
115115
"""Decides which type of credentials to return based on the given config.
116116
117117
Args:

0 commit comments

Comments
 (0)