0

I learned a tricks to pass functions as argument

def remove_punctuation(value):
    return re.sub('[!#?]', '', value)

clean_ops = [str.strip, remove_punctuation, str.title]

def clean_strings(strings, ops):
    result = []
    for value in strings:
        for function in ops:
            value = function(value)
        result.append(value)
    return result

print(clean_strings(states, clean_ops))

I find it amazing to encapsulate required functions to a list which even helps in the thinking process.

What's the pattern of the such a practice?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 2
    @jpp Design pattern. By the way, I think they're looking for a ["pipeline"](https://en.wikipedia.org/wiki/Pipeline_(software)). – cs95 May 14 '18 at 00:43
  • 1
    As a separate (related?) issue, it's a good idea to [compose](https://stackoverflow.com/questions/16739290/composing-functions-in-python) your functions into one rather than apply them sequentially in a `for` loop. – jpp May 14 '18 at 00:46
  • ty. I struggle to think out an abstract concept as 'compose' to describe such a context. @jpp – AbstProcDo May 14 '18 at 00:52
  • David Beazley has a fantastic talk on this subject. You can find the slides here: https://www.dabeaz.com/generators/ – Patrick Haugh May 14 '18 at 01:07

0 Answers0