Search code examples
pythongoogle-cloud-storagef-string

google cloud doesn't work with previous f-string python


I'm trying to connect to google cloud and i've set the python code as follows:

import google.cloud import storage

bucket_id='my_bucketname'
//others variables
storage=f'gs://{bucket_id}/'

client = storage.Client()

But, I've had the error:

client = storage.Client()
    AttributeError: 'str' object has no attribute 'Client'

I've noticed when I comment the variables with f-string(or using .format() as well), it works. These tests I did, there is no variable related with the method storage.Client() and even so occours the error.

I tested in 3.6 and 3.8 python versions with same errors.


Solution

  • This line of code imports the Google Cloud SDK into an object named storage.

    import google.cloud import storage
    

    You then declare a string named storage with the contents of the bucket name. This overwrites the previous line of code.

    storage=f'gs://{bucket_id}/'
    

    You are then trying to create a Cloud Storage Client object from a string object:

    client = storage.Client()
    

    That results in the error message:

    AttributeError: 'str' object has no attribute 'Client'
    

    Solution: use different variable names:

    import google.cloud import storage
    
    bucket_name='my_bucketname'
    //others variables
    bucket_uri=f'gs://{bucket_id}/'
    
    client = storage.Client()