Skip to content

Commit

Permalink
cleanup: f-string formatting (#789)
Browse files Browse the repository at this point in the history
* cleanup: f-string formatting

* cleanup: f-string formatting

* remove unnecessary :d specifier

Co-authored-by: Mariatta Wijaya <Mariatta@users.noreply.github.com>

* remove unnecessary :d specifier

Co-authored-by: Mariatta Wijaya <Mariatta@users.noreply.github.com>

* cleanup: f-string formatting

* cleanup: f-string formatting

Co-authored-by: Mariatta Wijaya <Mariatta@users.noreply.github.com>
  • Loading branch information
zabop and Mariatta committed May 16, 2022
1 parent 1b4413c commit 3664dde
Show file tree
Hide file tree
Showing 100 changed files with 403 additions and 489 deletions.
12 changes: 6 additions & 6 deletions docs/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,7 @@ def policy_document(client):

# Generate an upload form using the form fields.
policy_fields = "".join(
'<input type="hidden" name="{key}" value="{value}">'.format(
key=key, value=value
)
f'<input type="hidden" name="{key}" value="{value}">'
for key, value in policy.items()
)

Expand Down Expand Up @@ -301,13 +299,15 @@ def main():
client = storage.Client()
for example in _find_examples():
to_delete = []
print("%-25s: %s" % _name_and_doc(example))
name, doc = _name_and_doc(example)
print(f"{name:>25}: {doc}")

try:
example(client, to_delete)
except AssertionError as failure:
print(" FAIL: %s" % (failure,))
print(f" FAIL: {failure}")
except Exception as error: # pylint: disable=broad-except
print(" ERROR: %r" % (error,))
print(f" ERROR: {error!r}")
for item in to_delete:
item.delete()

Expand Down
8 changes: 3 additions & 5 deletions google/cloud/storage/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,14 +519,12 @@ def _raise_if_more_than_one_set(**kwargs):
:raises: :class:`~ValueError` containing the fields that were set
"""
if sum(arg is not None for arg in kwargs.values()) > 1:
escaped_keys = ["'%s'" % name for name in kwargs.keys()]
escaped_keys = [f"'{name}'" for name in kwargs.keys()]

keys_but_last = ", ".join(escaped_keys[:-1])
last_key = escaped_keys[-1]

msg = "Pass at most one of {keys_but_last} and {last_key}".format(
keys_but_last=keys_but_last, last_key=last_key
)
msg = f"Pass at most one of {keys_but_last} and {last_key}"

raise ValueError(msg)

Expand All @@ -548,7 +546,7 @@ def _bucket_bound_hostname_url(host, scheme=None):
if url_parts.scheme and url_parts.netloc:
return host

return "{scheme}://{host}/".format(scheme=scheme, host=host)
return f"{scheme}://{host}/"


def _api_core_retry_to_resumable_media_retry(retry, num_retries=None):
Expand Down
4 changes: 2 additions & 2 deletions google/cloud/storage/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ def __init__(self, client, client_info=None, api_endpoint=None):
# TODO: When metrics all use gccl, this should be removed #9552
if self._client_info.user_agent is None: # pragma: no branch
self._client_info.user_agent = ""
agent_version = "gcloud-python/{}".format(__version__)
agent_version = f"gcloud-python/{__version__}"
if agent_version not in self._client_info.user_agent:
self._client_info.user_agent += " {} ".format(agent_version)
self._client_info.user_agent += f" {agent_version} "

API_VERSION = "v1"
"""The version of the API, used in building the API call's URL."""
Expand Down
14 changes: 6 additions & 8 deletions google/cloud/storage/_signing.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,7 @@ def get_expiration_seconds_v4(expiration):
seconds = int(expiration.total_seconds())

if seconds > SEVEN_DAYS:
raise ValueError(
"Max allowed expiration interval is seven days {}".format(SEVEN_DAYS)
)
raise ValueError(f"Max allowed expiration interval is seven days {SEVEN_DAYS}")

return seconds

Expand Down Expand Up @@ -252,7 +250,7 @@ def canonicalize_v2(method, resource, query_parameters, headers):
for key, value in query_parameters.items()
)
encoded_qp = urllib.parse.urlencode(normalized_qp)
canonical_resource = "{}?{}".format(resource, encoded_qp)
canonical_resource = f"{resource}?{encoded_qp}"
return _Canonical(method, canonical_resource, normalized_qp, headers)


Expand Down Expand Up @@ -550,8 +548,8 @@ def generate_signed_url_v4(
ensure_signed_credentials(credentials)
client_email = credentials.signer_email

credential_scope = "{}/auto/storage/goog4_request".format(datestamp)
credential = "{}/{}".format(client_email, credential_scope)
credential_scope = f"{datestamp}/auto/storage/goog4_request"
credential = f"{client_email}/{credential_scope}"

if headers is None:
headers = {}
Expand Down Expand Up @@ -689,7 +687,7 @@ def _sign_message(message, access_token, service_account_email):

if response.status != http.client.OK:
raise exceptions.TransportError(
"Error calling the IAM signBytes API: {}".format(response.data)
f"Error calling the IAM signBytes API: {response.data}"
)

data = json.loads(response.data.decode("utf-8"))
Expand All @@ -706,7 +704,7 @@ def _url_encode(query_params):
:returns: URL encoded query params.
"""
params = [
"{}={}".format(_quote_param(name), _quote_param(value))
f"{_quote_param(name)}={_quote_param(value)}"
for name, value in query_params.items()
]

Expand Down
12 changes: 5 additions & 7 deletions google/cloud/storage/acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ def __str__(self):
return "{acl.type}-{acl.identifier}".format(acl=self)

def __repr__(self):
return "<ACL Entity: {acl} ({roles})>".format(
acl=self, roles=", ".join(self.roles)
)
return f"<ACL Entity: {self} ({', '.join(self.roles)})>"

def get_roles(self):
"""Get the list of roles permitted by this entity.
Expand Down Expand Up @@ -242,7 +240,7 @@ def validate_predefined(cls, predefined):
"""
predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined)
if predefined and predefined not in cls.PREDEFINED_JSON_ACLS:
raise ValueError("Invalid predefined ACL: %s" % (predefined,))
raise ValueError(f"Invalid predefined ACL: {predefined}")
return predefined

def reset(self):
Expand Down Expand Up @@ -285,7 +283,7 @@ def entity_from_dict(self, entity_dict):
entity = self.entity(entity_type=entity_type, identifier=identifier)

if not isinstance(entity, _ACLEntity):
raise ValueError("Invalid dictionary: %s" % entity_dict)
raise ValueError(f"Invalid dictionary: {entity_dict}")

entity.grant(role)
return entity
Expand Down Expand Up @@ -770,7 +768,7 @@ def client(self):
@property
def reload_path(self):
"""Compute the path for GET API requests for this ACL."""
return "%s/%s" % (self.bucket.path, self._URL_PATH_ELEM)
return f"{self.bucket.path}/{self._URL_PATH_ELEM}"

@property
def save_path(self):
Expand Down Expand Up @@ -809,7 +807,7 @@ def client(self):
@property
def reload_path(self):
"""Compute the path for GET API requests for this ACL."""
return "%s/acl" % self.blob.path
return f"{self.blob.path}/acl"

@property
def save_path(self):
Expand Down
16 changes: 7 additions & 9 deletions google/cloud/storage/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ def __init__(self, method, uri, headers, body):
headers["Content-Length"] = len(body)
if body is None:
body = ""
lines = ["%s %s HTTP/1.1" % (method, uri)]
lines.extend(
["%s: %s" % (key, value) for key, value in sorted(headers.items())]
)
lines = [f"{method} {uri} HTTP/1.1"]
lines.extend([f"{key}: {value}" for key, value in sorted(headers.items())])
lines.append("")
lines.append(body)
payload = "\r\n".join(lines)
Expand All @@ -86,7 +84,7 @@ def get(key, default=None):
:raises: :class:`KeyError` always since the future is intended to fail
as a dictionary.
"""
raise KeyError("Cannot get(%r, default=%r) on a future" % (key, default))
raise KeyError(f"Cannot get({key!r}, default={default!r}) on a future")

def __getitem__(self, key):
"""Stand-in for dict[key].
Expand All @@ -97,7 +95,7 @@ def __getitem__(self, key):
:raises: :class:`KeyError` always since the future is intended to fail
as a dictionary.
"""
raise KeyError("Cannot get item %r from a future" % (key,))
raise KeyError(f"Cannot get item {key!r} from a future")

def __setitem__(self, key, value):
"""Stand-in for dict[key] = value.
Expand All @@ -111,7 +109,7 @@ def __setitem__(self, key, value):
:raises: :class:`KeyError` always since the future is intended to fail
as a dictionary.
"""
raise KeyError("Cannot set %r -> %r on a future" % (key, value))
raise KeyError(f"Cannot set {key!r} -> {value!r} on a future")


class _FutureResponse(requests.Response):
Expand Down Expand Up @@ -257,7 +255,7 @@ def finish(self):
"""
headers, body, timeout = self._prepare_batch_request()

url = "%s/batch/storage/v1" % self.API_BASE_URL
url = f"{self.API_BASE_URL}/batch/storage/v1"

# Use the private ``_base_connection`` rather than the property
# ``_connection``, since the property may be this
Expand Down Expand Up @@ -332,7 +330,7 @@ def _unpack_batch_response(response):

subresponse = requests.Response()
subresponse.request = requests.Request(
method="BATCH", url="contentid://{}".format(content_id)
method="BATCH", url=f"contentid://{content_id}"
).prepare()
subresponse.status_code = int(status)
subresponse.headers.update(msg_headers)
Expand Down
32 changes: 13 additions & 19 deletions google/cloud/storage/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def __repr__(self):
else:
bucket_name = None

return "<Blob: %s, %s, %s>" % (bucket_name, self.name, self.generation)
return f"<Blob: {bucket_name}, {self.name}, {self.generation}>"

@property
def path(self):
Expand Down Expand Up @@ -575,20 +575,16 @@ def generate_signed_url(
quoted_name = _quote(self.name, safe=b"/~")

if virtual_hosted_style:
api_access_endpoint = "https://{bucket_name}.storage.googleapis.com".format(
bucket_name=self.bucket.name
)
api_access_endpoint = f"https://{self.bucket.name}.storage.googleapis.com"
elif bucket_bound_hostname:
api_access_endpoint = _bucket_bound_hostname_url(
bucket_bound_hostname, scheme
)
else:
resource = "/{bucket_name}/{quoted_name}".format(
bucket_name=self.bucket.name, quoted_name=quoted_name
)
resource = f"/{self.bucket.name}/{quoted_name}"

if virtual_hosted_style or bucket_bound_hostname:
resource = "/{quoted_name}".format(quoted_name=quoted_name)
resource = f"/{quoted_name}"

if credentials is None:
client = self._require_client(client)
Expand Down Expand Up @@ -840,7 +836,7 @@ def _get_download_url(
hostname = _get_host_name(client._connection)
base_url = _DOWNLOAD_URL_TEMPLATE.format(hostname=hostname, path=self.path)
if self.generation is not None:
name_value_pairs.append(("generation", "{:d}".format(self.generation)))
name_value_pairs.append(("generation", f"{self.generation:d}"))
else:
base_url = self.media_link

Expand Down Expand Up @@ -3095,7 +3091,7 @@ def get_iam_policy(
query_params["optionsRequestedPolicyVersion"] = requested_policy_version

info = client._get_resource(
"%s/iam" % (self.path,),
f"{self.path}/iam",
query_params=query_params,
timeout=timeout,
retry=retry,
Expand Down Expand Up @@ -3151,7 +3147,7 @@ def set_iam_policy(
if self.user_project is not None:
query_params["userProject"] = self.user_project

path = "{}/iam".format(self.path)
path = f"{self.path}/iam"
resource = policy.to_api_repr()
resource["resourceId"] = self.path
info = client._put_resource(
Expand Down Expand Up @@ -3207,7 +3203,7 @@ def test_iam_permissions(
if self.user_project is not None:
query_params["userProject"] = self.user_project

path = "%s/iam/testPermissions" % (self.path,)
path = f"{self.path}/iam/testPermissions"
resp = client._get_resource(
path,
query_params=query_params,
Expand Down Expand Up @@ -3462,7 +3458,7 @@ def compose(
)

api_response = client._post_resource(
"{}/compose".format(self.path),
f"{self.path}/compose",
request,
query_params=query_params,
timeout=timeout,
Expand Down Expand Up @@ -3595,7 +3591,7 @@ def rewrite(
if_source_metageneration_not_match=if_source_metageneration_not_match,
)

path = "{}/rewriteTo{}".format(source.path, self.path)
path = f"{source.path}/rewriteTo{self.path}"
api_response = client._post_resource(
path,
self._properties,
Expand Down Expand Up @@ -3712,7 +3708,7 @@ def update_storage_class(
(Optional) How to retry the RPC. See: :ref:`configuring_retries`
"""
if new_class not in self.STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
raise ValueError(f"Invalid storage class: {new_class}")

# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
Expand Down Expand Up @@ -3755,7 +3751,7 @@ def open(
encoding=None,
errors=None,
newline=None,
**kwargs
**kwargs,
):
r"""Create a file handler for file-like I/O to or from this blob.
Expand Down Expand Up @@ -4448,9 +4444,7 @@ def _raise_from_invalid_response(error):
else:
error_message = str(error)

message = "{method} {url}: {error}".format(
method=response.request.method, url=response.request.url, error=error_message
)
message = f"{response.request.method} {response.request.url}: {error_message}"

raise exceptions.from_http_status(response.status_code, message, response=response)

Expand Down

0 comments on commit 3664dde

Please sign in to comment.