IDE 代码补全

VS Code 和 PyCharm 等 IDE 为 Python 语言提供内置 代码补全功能。

google-ads-python 库在运行时使用 getter methods on the GoogleAdsClient class 动态生成 protobuf 消息类,这可能会抑制依赖于源代码静态分析的 IDE 代码补全功能。

如需提高与依赖于静态分析的代码补全工具的兼容性,您可以执行以下任一操作:

  1. 将类型注解与动态 getter 方法 搭配使用(推荐)。
  2. 直接导入 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()

直接导入的缺点

虽然直接导入生成的类有助于代码补全,但也会带来一些缺点:

  1. 难以定位: 您不一定能清楚地知道给定类所在的模块,因此很难找到正确的导入路径。
  2. 升级后容易出错: 生成的类的目录结构可能会随着客户端库的新版本而发生变化。如果您直接导入类,则代码可能会在升级时中断,而使用 getter 方法的代码不受此类更改的影响。
  3. 需要手动初始化: 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,
    )