Python: Execute function only if parametrized

2017-02-18 10:37

I recently created a script based on the simple log parsing pipeline to analyse some Apache webserver logfiles.

To get specific data out the script was equipped with various function to apply filters. All those were optional and I ended up equipping all those functions with something like the following:

def filter_something(requests, parameter):
    if not parameter:
        yield from requests
        return

    for request in requests:
        # Use parameter for filtering ...
        yield request

To get rid of this I wrote a simple decorator:

from functools import wraps

def if_parametrized(func):
    def returner(requests):
        yield from requests

    @wraps(func)
    def only_if_parametrized(requests, *params):
        if not any(params):
            return returner(requests)

        return func(requests, *params)

    return only_if_parametrized

Now I can skip the duplicated check for the parameters and get some cleaner code:

@if_parametrized
def filter_something(requests, parameter):
    for request in requests:
        # Use parameter for filtering ...
    yield request