Ugly mutable parts of Python

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I like Python more than PHP, but the mutable parts of Python are as ugly as PHP. This function is an exampe:

def transform_words(content, targets, transform):
    """Return a string based on *content* but with each occurrence 
    of words in *targets* replaced with
    the result of applying *transform* to it."""
    result = ''
    for word in content.split():
        if word in targets:
            result += ' {}'.format(transform(word))
        else:
            result += ' {}'.format(word)
    return result

Stuff like setting up a string to be modified:

result = ”

and then:

result += ‘ {}’.format(transform(word))

Ugly!

I am aware that the function is for demonstration purposes only.

Post external references

  1. 1
    http://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/
Source