Could be a basic one:
I am just trying to do multiple operations on one of the key in a dictionary with encoding the first element of the key, splitting it further based on a character and also joining with another string as below:
images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
Code snippet in which I am doing the above formatting:
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests
@require_http_methods(["GET"])
def images_info(request):
response = requests.get("http://127.0.0.1:6000/images/json")
table = []
images_list = {}
for image in response.json():
try:
images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8")
except TypeError:
images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
images_list["Id"] = image["Id"].encode("utf-8")[7:19]
table.append(images_list)
images_list = {}
return JsonResponse(table,safe=False)
Can someone tell me whether is it the right way to do these many operations in a single line? or in another way Does it follows the python standards ?
If not does python standards suggest any limited operations in a single line or so?
Reason for asking this is that the number of characters should not exceed 79 characters as per pep-8.
There's nothing wrong with chaining a few string operations together. If you want to keep it within the 80-character line, just add some parentheses:
images_list["RepoTag"] = (
image["RepoDigests"][0].encode("utf-8").split("@")[0] +
":none")
or use str.format()
to provide those same parentheses:
images_list["RepoTag"] = '{}:none'.format(
image["RepoDigests"][0].encode("utf-8").split("@")[0])
You could, otherwise, trivially use a local variable:
first_digest = image["RepoDigests"][0].encode("utf-8")
images_list["RepoTag"] = '{}:none'.format(first_digest.split("@")[0])