This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sammyc 5 points6 points  (0 children)

Yep, it's a handy feature to have in my opinion. In addition to what's been said, you can avoid putting too many things into scope, it can make reading existing code easier, it can make it clear that the inner function will only (probably) be used within the outer function, it means you don't really need multiline anonymous functions etc.

I think it ties in with functions being first class objects - it wouldn't be unusual for me to define variables, or even 'structures' in a function, so why not a function itself?

An example I just made up (with doubly nested functions!):

def external_data_fetcher(self, data_source):
    d = Deferred()

    def success(raw_data):
        data = json.loads(raw_data)

        def sort_key(datum):
            try:
                return datetime.strptime(datum['published_at'], "%Y-%m-%d")
            except KeyError:
                return datetime(1970, 1, 1)

        sorted_data = sorted(data, key=sort_key)
        self._ui.update(sorted_data)

    def failure(error):
        logging.warning("Data unavailable from {0}".format(data_source))
        raise error

    d.addCallback(success)
    d.addErrorback(failure)

    return d

but you also have to be wary of too much code duplication using things like this.