DEV Community

Stephen Bawks
Stephen Bawks

Posted on

Loops... where we are going we don't need loops

Here is hopefully the first of many... on several different coding and IAC topics.

There is nothing against loops, however one of the main challenges with them is sometimes it can be especially difficult to iterate through when you may have several conditional if statements or different bits of logic happening in the loop.

Wanted to touch on map() in Python. As its one of my new favorite things to reduce some of the amount of code when it concerns needing a for loop.

The map() is defined as the following:

map(function, iterable[, iterable1, iterable2,..., iterableN])
Enter fullscreen mode Exit fullscreen mode

With the map() function, you can see that there is two things going on here. There is a function and then an object that you are passing in. The object you are passing in can also be a list, tuple, etc.

In my example, I am taking in a list of scopes that is coming from a variables file that is being passed in to be consumed for an infrastructure as code module. I need to format the scopes in a certain fashion that will then be applied to an API Gateway.

In the example below I have a pretty simple amount of code that I have used to format, parse and structure a set of scopes that I needed to be applied to my API.

API_SCOPES = "read:stuff, write:stuff, delete:stuff"
Enter fullscreen mode Exit fullscreen mode

Just to add in some extra protections where someone may have added some white space, aka spaces, into the string. I added an extra statement to remove any additional spacing and then I am spliting on commas.

['read:stuff', 'write:stuff', 'delete:stuff']
Enter fullscreen mode Exit fullscreen mode

The result is a list that has all of the scopes from the original comma separated string.

API_SCOPES = "read:stuff, write:stuff, delete:stuff"
DOMAIN_NAME = "api.example.com"

def api_authorization_scopes(name: str) -> str:
    """
    Takes a string of scopes and returns a list of properly formatted scopes.

    Args:
        name (str): The scope string

    Returns:
        Optional[str]: Formatted scope string

    """
    return f"https://{DOMAIN_NAME}/{name}"

parsed_scopes = API_SCOPES.replace(' ', '').split(",")
allowed_oauth_scopes = map(api_authorization_scopes, parsed_scopes)
Enter fullscreen mode Exit fullscreen mode

This results in a map object that I can output as a list and it looks like the following.

['https://api.example.com/read:stuff', 'https://api.example.com/write:stuff', 'https://api.example.com/delete:stuff']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)