VS Code 和 PyCharm 等 IDE 提供 Python 語言的內建程式碼完成功能。
google-ads-python 程式庫會在執行階段使用 GoogleAdsClient 類別的 getter 方法,動態產生 protobuf 訊息類別,這可能會抑制 IDE 程式碼自動完成功能,因為這類功能依賴來源程式碼的靜態分析。
如要提升與依賴靜態分析的程式碼自動完成工具的相容性,請直接匯入 Protobuf 訊息類別,而非使用 getter 方法。
使用動態匯入的 protobuf 訊息類別。這種方法通常與程式碼自動完成工具不相容。
from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_storage() # The Campaign class is imported dynamically, preventing the IDE from # reading the class definition. campaign = client.get_type("Campaign")使用直接匯入的 protobuf 訊息類別。這種方法可讓程式碼自動完成工具正常運作。
from google.ads.googleads.v22.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方法會先初始化服務,然後再傳回服務。如果直接匯入服務,您必須先手動初始化服務,才能提出要求。