A set() could solve the problem.
A set is a collection of unique items, where the order is not kept.
Adding items to a set -> slow
Looking up items in a set -> blazing fast
Containment checking of a set -> also fast
You can't use index access on a set.
Here the modified code:
If the conv_id is repeating, you should check this, before you call attachments.
Here is an updated version which may work with your code.
The thing is, you use the camel case names for objects and this is not very Pythonic (PEP8).
With pathlib the handling with paths is easier and compatible on all platforms.
He also complains about naming.
A set is a collection of unique items, where the order is not kept.
Adding items to a set -> slow
Looking up items in a set -> blazing fast
Containment checking of a set -> also fast
You can't use index access on a set.
Here the modified code:
def attachments(attach, conv_id): convId = str(conv_id) processed = set() for item in attach: if item in processed: continue attachId = str(item['id']) attachParams = {'id': attachId} response = requests.get(attachUrl + attachId, headers=h, params=attachParams) response = response.content responseParsed = json.loads(response) content = b64decode(responseParsed['contents']) fileName = responseParsed['friendlyName'] with open(r'attachments/' + convId + '_' + fileName + '.jpg', 'wb') as k: k.write(content) processed.add(item)If it's not the
item
from attach
which repeats, then use the other object.If the conv_id is repeating, you should check this, before you call attachments.
Here is an updated version which may work with your code.
The thing is, you use the camel case names for objects and this is not very Pythonic (PEP8).
With pathlib the handling with paths is easier and compatible on all platforms.
from pathlib import Path def attachments(attach, conv_id): processed = set() for item in attach: if item in processed: continue attach_id = item['id'] attach_params = {'id': attach_id} response = requests.get(attachUrl + attach_id, headers=h, params=attach_params) response = response.content response_parsed = json.loads(response) content = b64decode(response_parsed['contents']) friendly_name = responseParsed['friendlyName'] file_name = f"convId_{friendly_name}.jpg" attachment = "attachments" / Path(file_name) with attachment.open("wb") as fd: fd.write(content) processed.add(item)If you use an IDE like PyCharm, the names which have no definition, will be red underlined.
He also complains about naming.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!