Last Updated: February 25, 2016
· calsaverini
2010 12 08 130808

Reducing boilerplate in string generation functions in python

If you have repetitive code that generates strings you can greatly reduce boilerplate by using the function locals(), which returns a dictionary with the current local variables in a function, and the format() method, which is the current preferred method for string formatting.

As an example, consider the following function:

def generate_address(street, number, district, city, state, zipcode):
    address = """
    {street}, {number} - {district} 
    {city} - {state}        {zipcode}
    return address
Say Thanks