Python使用f-string赋值后调用Google Cloud storage.Client报错AttributeError
问题原因
你的报错核心是变量名冲突覆盖了已导入的模块对象,和你用的f-string、format语法或者Python版本没有关系:
- 你代码中最初导入Google Cloud Storage模块时(你原代码的导入写法存在笔误,标准写法为
from google.cloud import storage),storage变量指向的是GCS的模块对象,可以正常调用Client方法。 - 后续你执行了
storage=f'gs://{bucket_id}/'这行代码,相当于把storage这个变量名重新赋值为了字符串类型的存储路径,原有的模块引用被直接覆盖。 - 当运行到
client = storage.Client()时,此时的storage已经是字符串对象,字符串类型本身没有Client属性,就会抛出你看到的AttributeError。
你注释掉f-string那行代码后恢复正常,就是因为此时storage没有被重新赋值,仍然指向导入的GCS模块,自然可以正常调用方法。
解决方法
只需要把存储路径的变量名更换为不会和导入模块重名的名称即可,比如storage_path、bucket_uri等,修改后的代码示例如下:
from google.cloud import storage bucket_id='my_bucketname' // 其他变量定义 storage_path = f'gs://{bucket_id}/' client = storage.Client()
内容的提问来源于stack exchange,提问作者Pinheiro
相关产品推荐
相关产品推荐

