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方法会在返回服务之前对其进行初始化。如果您直接导入服务,则需要在发出请求之前手动初始化这些服务。