VS Code 和 PyCharm 等 IDE 提供 Python 語言的內建程式碼補全功能。
google-ads-python 程式庫會在執行階段,使用 GoogleAdsClient 類別的getter 方法動態產生 protobuf 訊息類別,這可能會阻礙 IDE 程式碼自動完成功能,因為這類功能仰賴原始碼的靜態分析。
如要提升與依賴靜態分析的程式碼完成工具的相容性,您可以採取下列任一做法:
- 搭配使用型別註解和動態 getter 方法 (建議做法)。
- 直接匯入 protobuf 訊息類別和服務用戶端。
含型別提示的動態匯入
使用動態匯入功能,可確保程式碼在程式庫更新時仍能保持彈性。新增類型註解可啟用 IDE 程式碼自動完成功能,同時保留動態初始化的優點:
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.v26.resources.types.campaign import (
Campaign,
)
client = GoogleAdsClient.load_from_storage()
# Type hints allow the IDE to provide code completion suggestions while
# retaining dynamic class generation.
campaign: Campaign = client.get_type("Campaign")
直接匯入
您也可以直接匯入 protobuf 訊息類別。這種方法可讓 IDE 程式碼自動完成功能立即生效,不必使用 getter 方法:
from google.ads.googleads.v26.resources import Campaign
# The Campaign class is imported directly, enabling the IDE to read the
# class definition and make code completion suggestions.
campaign = Campaign()
直接匯入的缺點
雖然直接匯入產生的類別有助於補全程式碼,但也會帶來一些取捨:
- 難以找到:不一定能清楚看出特定類別位於哪個模組,因此可能難以找到正確的匯入路徑。
- 升級時容易出錯:產生類別的目錄結構可能會隨著用戶端程式庫的新版本而變更。如果直接匯入類別,程式碼可能會在升級時中斷,而使用 getter 方法的程式碼則不受這類變更影響。
需要手動初始化:
get_service方法會先使用驗證、傳輸設定和 gRPC 攔截器 (附加login-customer-id和linked-customer-id等標頭、處理記錄,並將錯誤包裝在GoogleAdsException中) 初始化服務,然後再傳回服務。如果直接匯入及例項化服務,系統會略過這些攔截器,您必須手動設定憑證和傳輸管道:from google.ads.googleads.v26.services.services import ( campaign_service as campaign_service_module, ) # Dynamic service getter (initializes credentials, transport, and gRPC # interceptors automatically). campaign_service = client.get_service("CampaignService") # Direct service client import (requires manual credential and interceptor # configuration). campaign_service_client = campaign_service_module.CampaignServiceClient( credentials=client.credentials, )