Error message

  • Notice: Trying to get property of non-object in filter_default_format() (line 532 of /home/ntroutman/webapps/nt_drupal/modules/filter/filter.module).
  • Notice: Undefined variable: options in filter_process_format() (line 911 of /home/ntroutman/webapps/nt_drupal/modules/filter/filter.module).

Function Closures in Python

So today I used my first function closure in Python. I had always wondered why/how someone would use them, but today after reading an article earlier this morning I ran across a place to use them while coding this evening. Here we go:

def __getNeighbors(func):
    def getNeighborsHelper(self, *args, **kwargs):
        neighbor_level = kwargs.get('neighbor_level', args[-1])
        if type(neighbor_level) in (list, tuple):
            all = []
            for level in neighbor_level:
               all.append(func(self, *args, **kwargs))           
            return all
        else:
            return func(self, *args, **kwargs)
    return getNeighborsHelper

getTightHullNearestNeighbors = __getNeighbors(lambda self, neighbor_level: \
    tight_hull_nearest[self][neighbor_level])       
getTightHullAllNeighbors = __getNeighbors(lambda self, neighbor_level: \
    tight_hull_all[self][neighbor_level])
getNeighborsWithinDistance = __getNeighbors( \
    lambda self, distance, neighbor_level: \
        [site for site in sites_sorted_by_distance \
            if site.distanceTo(self) <= distance])

The idea here is that the various get_______Neighbors functions will return either a single list of neighbors or a list of lists of neighbors depending upon if "neighbor_level" is itself a single int or a list of ints. And then each function gets the neighbors in a slightly different way.

So there you go, function closures, lambda functions and list comprehensions all in one example.

Comments

Nice post. Just a quick syntactic tip to make your code look prettier: there's no need to put all those backslashes. Insite a pair of parenthesis, braces or brackets, the Python parser treats all newlines as if they were plain spaces. Try it, and you will realize we almost never really need to use backslashes for line continuation in Python.

I am the computer user i have just a idea of clouser proming function because i am the student of a+ certification i have with your point of view unction closures, lambda functions and list comprehensions all in one example.

I am the computer user i have just a idea of clouser proming function because i am the student of a+ certification i have with your point of view unction closures, lambda functions and list comprehensions all in one example.

Add new comment