Skip to content

Commit 0abd014

Browse files
google-labs-jules[bot]BenRKarl
authored andcommitted
I've added type hints to the examples/recommendations directory.
This change adds type hints and annotations to the Python files in the examples/recommendations directory. This improves code readability and helps with static analysis. The following files were modified: - detect_and_apply_recommendations.py - dismiss_recommendation.py - generate_budget_recommendations.py - get_recommendation_impact_metrics.py
1 parent 5b11e15 commit 0abd014

File tree

4 files changed

+132
-52
lines changed

4 files changed

+132
-52
lines changed

examples/recommendations/detect_and_apply_recommendations.py

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,18 @@
3131

3232
import argparse
3333
import sys
34+
from typing import List
3435

3536
from google.ads.googleads.client import GoogleAdsClient
3637
from google.ads.googleads.errors import GoogleAdsException
38+
from google.ads.googleads.v19.services.types.google_ads_service import GoogleAdsRow
39+
from google.ads.googleads.v19.services.types.recommendation_service import (
40+
ApplyRecommendationOperation,
41+
ApplyRecommendationResult,
42+
)
3743

3844

39-
def main(client, customer_id):
45+
def main(client: GoogleAdsClient, customer_id: str) -> None:
4046
"""The main method that creates all necessary entities for the example.
4147
4248
Args:
@@ -46,7 +52,9 @@ def main(client, customer_id):
4652
detect_and_apply_recommendations(client, customer_id)
4753

4854

49-
def detect_and_apply_recommendations(client, customer_id):
55+
def detect_and_apply_recommendations(
56+
client: GoogleAdsClient, customer_id: str
57+
) -> None:
5058
"""Detects recommendations and applies them.
5159
5260
Args:
@@ -56,7 +64,7 @@ def detect_and_apply_recommendations(client, customer_id):
5664

5765
# [START detect_keyword_recommendations]
5866
googleads_service = client.get_service("GoogleAdsService")
59-
query = f"""
67+
query: str = f"""
6068
SELECT
6169
recommendation.campaign,
6270
recommendation.keyword_recommendation
@@ -65,10 +73,12 @@ def detect_and_apply_recommendations(client, customer_id):
6573
recommendation.type = KEYWORD"""
6674

6775
# Detects keyword recommendations that exist for the customer account.
68-
response = googleads_service.search(customer_id=customer_id, query=query)
76+
response: Iterable[GoogleAdsRow] = googleads_service.search(
77+
customer_id=customer_id, query=query
78+
)
6979

70-
operations = []
71-
for row in response.results:
80+
operations: List[ApplyRecommendationOperation] = []
81+
for row in response:
7282
recommendation = row.recommendation
7383
print(
7484
f"Keyword recommendation ('{recommendation.resource_name}') "
@@ -94,12 +104,13 @@ def detect_and_apply_recommendations(client, customer_id):
94104

95105

96106
# [START build_apply_recommendation_operation]
97-
def build_recommendation_operation(client, recommendation):
107+
def build_recommendation_operation(
108+
client: GoogleAdsClient, recommendation: str
109+
) -> ApplyRecommendationOperation:
98110
"""Creates a ApplyRecommendationOperation to apply the given recommendation.
99111
100112
Args:
101113
client: an initialized GoogleAdsClient instance.
102-
customer_id: a client customer ID.
103114
recommendation: a resource name for the recommendation to be applied.
104115
"""
105116
# If you have a recommendation ID instead of a resource name, you can create
@@ -110,7 +121,9 @@ def build_recommendation_operation(client, recommendation):
110121
# customer_id, recommendation.id
111122
# )
112123

113-
operation = client.get_type("ApplyRecommendationOperation")
124+
operation: ApplyRecommendationOperation = client.get_type(
125+
"ApplyRecommendationOperation"
126+
)
114127

115128
# Each recommendation type has optional parameters to override the
116129
# recommended values. Below is an example showing how to override a
@@ -127,7 +140,11 @@ def build_recommendation_operation(client, recommendation):
127140

128141

129142
# [START apply_recommendation]
130-
def apply_recommendations(client, customer_id, operations):
143+
def apply_recommendations(
144+
client: GoogleAdsClient,
145+
customer_id: str,
146+
operations: List[ApplyRecommendationOperation],
147+
) -> None:
131148
"""Applies a batch of recommendations.
132149
133150
Args:
@@ -137,20 +154,22 @@ def apply_recommendations(client, customer_id, operations):
137154
"""
138155
# Issues a mutate request to apply the recommendations.
139156
recommendation_service = client.get_service("RecommendationService")
140-
response = recommendation_service.apply_recommendation(
141-
customer_id=customer_id, operations=operations
157+
response: ApplyRecommendationResult = (
158+
recommendation_service.apply_recommendation(
159+
customer_id=customer_id, operations=operations
160+
)
142161
)
143162

144163
for result in response.results:
145164
print(
146165
"Applied a recommendation with resource name: "
147-
f"'{result[0].resource_name}'."
166+
f"'{result.resource_name}'."
148167
)
149168
# [END apply_recommendation]
150169

151170

152171
if __name__ == "__main__":
153-
parser = argparse.ArgumentParser(
172+
parser: argparse.ArgumentParser = argparse.ArgumentParser(
154173
description=(
155174
"Retrieves keyword recommendations for specified customer and "
156175
"applies them."
@@ -164,11 +183,17 @@ def apply_recommendations(client, customer_id, operations):
164183
required=True,
165184
help="The Google Ads customer ID.",
166185
)
167-
args = parser.parse_args()
186+
args: argparse.Namespace = parser.parse_args()
168187

169188
# GoogleAdsClient will read the google-ads.yaml configuration file in the
170189
# home directory if none is specified.
190+
<<<<<<< HEAD
171191
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
192+
=======
193+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
194+
version="v19"
195+
)
196+
>>>>>>> a90c77484 (I've added type hints to the examples/recommendations directory.)
172197

173198
try:
174199
main(googleads_client, args.customer_id)

examples/recommendations/dismiss_recommendation.py

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

2424
from google.ads.googleads.client import GoogleAdsClient
2525
from google.ads.googleads.errors import GoogleAdsException
26+
from google.ads.googleads.v19.services.services.recommendation_service import (
27+
RecommendationServiceClient,
28+
)
29+
from google.ads.googleads.v19.services.types.recommendation_service import (
30+
DismissRecommendationRequest,
31+
DismissRecommendationResponse,
32+
)
2633

2734

28-
def main(client, customer_id, recommendation_id):
29-
recommendation_service = client.get_service("RecommendationService")
30-
request = client.get_type("DismissRecommendationRequest")
35+
def main(
36+
client: GoogleAdsClient, customer_id: str, recommendation_id: str
37+
) -> None:
38+
recommendation_service: RecommendationServiceClient = client.get_service(
39+
"RecommendationService"
40+
)
41+
request: DismissRecommendationRequest = client.get_type(
42+
"DismissRecommendationRequest"
43+
)
3144
operation = request.DismissRecommendationOperation()
3245
operation.resource_name = recommendation_service.recommendation_path(
3346
customer_id, recommendation_id
3447
)
3548
request.customer_id = customer_id
3649
request.operations.append(operation)
3750

38-
response = recommendation_service.dismiss_recommendation(request=request)
51+
response: DismissRecommendationResponse = (
52+
recommendation_service.dismiss_recommendation(request=request)
53+
)
3954

4055
print(
4156
"Dismissed recommendation with resource name: "
@@ -44,7 +59,7 @@ def main(client, customer_id, recommendation_id):
4459

4560

4661
if __name__ == "__main__":
47-
parser = argparse.ArgumentParser(
62+
parser: argparse.ArgumentParser = argparse.ArgumentParser(
4863
description=("Dismisses a recommendation with the given ID.")
4964
)
5065
# The following argument(s) should be provided to run the example.
@@ -62,11 +77,13 @@ def main(client, customer_id, recommendation_id):
6277
required=True,
6378
help="The recommendation ID.",
6479
)
65-
args = parser.parse_args()
80+
args: argparse.Namespace = parser.parse_args()
6681

6782
# GoogleAdsClient will read the google-ads.yaml configuration file in the
6883
# home directory if none is specified.
69-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
84+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
85+
version="v20"
86+
)
7087

7188
try:
7289
main(googleads_client, args.customer_id, args.recommendation_id)

examples/recommendations/generate_budget_recommendations.py

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,33 @@
2727

2828
import argparse
2929
import sys
30+
from typing import List, Dict, Any
3031

3132
from google.ads.googleads.client import GoogleAdsClient
3233
from google.ads.googleads.errors import GoogleAdsException
34+
from google.ads.googleads.v18.services.services.recommendation_service import (
35+
RecommendationServiceClient,
36+
)
37+
from google.ads.googleads.v18.services.types.recommendation_service import (
38+
GenerateRecommendationsRequest,
39+
GenerateRecommendationsResponse,
40+
)
41+
from google.ads.googleads.v18.resources.types.recommendation import Recommendation
3342

3443

35-
def main(client, customer_id):
44+
def main(client: GoogleAdsClient, customer_id: str) -> None:
3645
"""The main method that creates all necessary entities for the example.
3746
3847
Args:
3948
client: an initialized GoogleAdsClient instance.
4049
customer_id: a client customer ID.
4150
"""
42-
recommendation_service = client.get_service("RecommendationService")
43-
request = client.get_type("GenerateRecommendationsRequest")
51+
recommendation_service: RecommendationServiceClient = client.get_service(
52+
"RecommendationService"
53+
)
54+
request: GenerateRecommendationsRequest = client.get_type(
55+
"GenerateRecommendationsRequest"
56+
)
4457

4558
request.customer_id = customer_id
4659
request.recommendation_types = ["CAMPAIGN_BUDGET"]
@@ -51,14 +64,16 @@ def main(client, customer_id):
5164
request.positive_locations_ids = [2840] # 2840 is for United States
5265
request.asset_group_info = [{"final_url": "https://www.your-company.com/"}]
5366

54-
results = recommendation_service.generate_recommendations(request)
67+
results: GenerateRecommendationsResponse = (
68+
recommendation_service.generate_recommendations(request)
69+
)
5570

56-
recommendations = results.recommendations
71+
recommendations: List[Recommendation] = results.recommendations
5772

5873
# Initialize a list to store all budget recommendations with impact metrics.
59-
budget_recommendations_list = []
74+
budget_recommendations_list: List[Dict[str, Any]] = []
6075
# Initialize a list to store budget recommendation amounts.
61-
budget_amounts = []
76+
budget_amounts: List[float] = []
6277

6378
# Get budget recommendations with their associated impact metrics.
6479
for rec in recommendations:
@@ -70,14 +85,14 @@ def main(client, customer_id):
7085
# budget amount best aligns with their goals.
7186
for budget_option in campaign_budget_rec.budget_options:
7287
impact = budget_option.impact
73-
budget_amount = budget_option.budget_amount_micros
74-
if budget_amount > 0:
75-
budget_data = {
76-
"budget_amount": round((budget_amount / 1000000), 2),
88+
budget_amount_micros = budget_option.budget_amount_micros
89+
if budget_amount_micros > 0:
90+
budget_data: Dict[str, Any] = {
91+
"budget_amount": round((budget_amount_micros / 1000000), 2),
7792
"potential_metrics": impact.potential_metrics,
7893
}
7994
budget_recommendations_list.append(budget_data)
80-
budget_amounts.append(round((budget_amount / 1000000), 2))
95+
budget_amounts.append(round((budget_amount_micros / 1000000), 2))
8196

8297
print(f"budget_recommendations_list:\n{budget_recommendations_list}")
8398
"""
@@ -96,7 +111,7 @@ def main(client, customer_id):
96111

97112

98113
if __name__ == "__main__":
99-
parser = argparse.ArgumentParser(
114+
parser: argparse.ArgumentParser = argparse.ArgumentParser(
100115
description=(
101116
"Generate budget recommendations for a Performance Max campaign."
102117
)
@@ -110,11 +125,13 @@ def main(client, customer_id):
110125
help="The Google Ads customer ID.",
111126
)
112127

113-
args = parser.parse_args()
128+
args: argparse.Namespace = parser.parse_args()
114129

115130
# GoogleAdsClient will read the google-ads.yaml configuration file in the
116131
# home directory if none is specified.
117-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
132+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
133+
version="v20"
134+
)
118135

119136
try:
120137
main(googleads_client, args.customer_id)

0 commit comments

Comments
 (0)