You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google storage.Client初始化报错:__init__仅接收2个位置参数但传入3个

问题描述

使用本地Google凭据认证访问Google Cloud Storage时触发报错:

TypeError: init() takes 2 positional arguments but 3 were given

运行如下最简代码即可复现该错误:

from google.cloud import storage
client = storage.Client()

已尝试的修复操作均未生效,包括:

  • 手动调用google.auth.default指定全量权限范围获取凭据
  • 显式调用storage.Client.__init__传入凭据、项目参数初始化客户端

当前环境相关依赖版本信息:

  • google-api-core 2.8.1(pypi源)
  • google-api-python-client 1.12.11(pypi源)
  • google-auth 1.35.0(conda-forge源)
  • google-auth-httplib2 0.1.0(conda-forge源)
  • google-auth-oauthlib 0.5.1(pypi源)
  • google-cloud 0.34.0(pypi源)
  • google-cloud-bigquery 3.1.0(pypi源)
  • google-cloud-bigquery-storage 2.13.1(pypi源)
  • google-cloud-core 2.3.0(pypi源)
  • google-cloud-sdk 387.0.0(conda-forge源,Python3.9适配)
  • google-cloud-storage 2.3.0(pypi源)
  • google-crc32c 1.1.2(Python3.9适配)
  • google-resumable-media 2.3.3(conda-forge源)
  • googleapis-common-protos 1.56.2(conda-forge源,Python3.9适配)
根因分析
  1. 环境中存在已废弃的历史依赖google-cloud 0.34.0,该2017年就停止维护的元包会和新版Google Cloud客户端库产生命名空间冲突,导致导入google.cloud.storage时加载到旧包内不兼容的Client类定义,触发参数数量不匹配的报错。
  2. 手动调用__init__方法的写法本身存在语法错误:__init__是类的实例初始化方法,不能脱离实例直接通过类名调用,传入未定义的self参数也会触发额外异常。
修复步骤
  1. 卸载冲突的废弃依赖:
pip uninstall -y google-cloud
# conda环境额外执行
conda remove -y google-cloud
  1. 升级核心依赖到兼容的稳定版本:
pip install --upgrade google-cloud-storage google-auth google-cloud-core
  1. 修正客户端初始化代码,无需手动调用google.auth.default,客户端会自动读取本地gcloud配置的应用默认凭据,最简写法即可正常运行:
from google.cloud import storage
client = storage.Client()

如果需要手动指定凭据,正确写法为将凭据作为参数传入Client构造方法,禁止直接调用__init__:

from google.cloud import storage
import google.auth

credentials, project = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
client = storage.Client(credentials=credentials, project=project)

内容的提问来源于stack exchange,提问作者ArinL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:27:24