Repeat a Python Function - execute the same number of times as entries in a list

62 Views Asked by At

Recently I found a python module for one of our COTS products (Tenable) here at the office. It was developed to help access the product's API. I have it installed in my lab here alongside Python 3.9.10 and based on my observations it is working ok. No problems executing simple code.

This product hosts file repositories that manage uploads from thousands of users. The Python module contains a specific function for making edits to those repositories. That function is very specific about the type of Python object that can be specified. For example, the id number has to be an integer. The name has to be a string, and the allowed IPs have to be a list, etc.

The exact challenge I am facing here is that I need to perform edits on 12 repositories. The data is stored in an external JSON file that I access via json.load.

I can successfully perform an edit (using information in the JSON) on a single repository.

This is how I did it:

x = sc.repositories.edit(repository_id=(repo_id[-1]), name=repo_name[-1], allowed_ips=(ip_list[-1]))

sc.repositories.edit is defined in the module. repo_id, repo_name, and allowed_ips are lists of data that come from the JSON. I then used the position [-1] to tell Python to plug in the last entries in the list. The API considers this a PATCH

This seems to work as expected. I can log into the web application and see the changes.

...but is there a way to repeat this function until it has sent the updates for all 12 repositories?

I can successfully send this using a [0], [-1], or other position. But the module won't accept slices and I don't know how to loop something this complicated.

Thanks in advance.

1

There are 1 best solutions below

1
On

If I understood you correctly, you could use zip, or even just a simple range-based for-loop:

for current_repo_id, current_repo_name, current_ips in zip(repo_id, repo_name, ip_list):
    x = sc.repositories.edit(
        repository_id=current_repo_id,
        name=current_repo_name,
        allowed_ips=current_ips
    )