Reputation: 1508
I'm working with Google Cloud Storage. One of its best practices is to reuse the clients. I've written several functions which I would like to be run with the possibility of not reusing the client.
The coder would be the one to decide that, by using the reuse_cl
variable.
I was wondering why the following script does not work:
def test_storage(bucket_name,reuse_cl=True):
if not reuse_cl:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
list_blobs = list(bucket.list_blobs())
if __name__ == "__main__":
storage_client = storage.Client()
test_storage(BUCKET_NAME)
If I comment out the if in the test_storage, then everything works out fine. Is there a way of making the script work, and preserve the ability to create a client inside the function?
Upvotes: 1
Views: 789
Reputation: 522
Posting comments from @furas and @John Hanley for better visibility:
You should change the parameters expected in the function, so that can receive the client instead of a flag. You can take the following approach to do so:
def test_storage(bucket_name, storage_client=None):
And when invoking the function you can do so with either:
test_storage(BUCKET_NAME, storage_client)
or
test_storage(BUCKET_NAME)
and add something like this to the function: if not storage_client: storage_client = storage.Client()
This way, you will create a client when you don't receive it on the invocation. However, you have to take into consideration if reusing client brings you enough benefits, and if they outweigh increased code complexity making it worth it.
Upvotes: 1