Binding frustration

Peter Otten __peter__ at web.de
Thu Sep 18 19:14:12 EDT 2003


Rob Hunter wrote:

> So it just occurred to me that probably, in this case, the Python way
> is the Scheme way:
> 
> def getGenres(title):
> 
>      def inGenre(g):
>          return <boolean test using g and title and the dictionary>
> 
>      return filter(inGenre, ['Comedy','Suspense', ...])
> 
> :)
> 
> But still, wrt my original complaint, doesn't it seem wrong that I
> couldn't write that program?
> 

Doesn't it strike you that the function name inGenre suggests a test rather
than a function with side effects? I think your second approach is clearer
than the workaround using result.append() that was suggested in previous
posts.

Why would you nest inGenre() inside getGenres(). Testing if a title is in
one specified genre is a useful application, too. Thus the title must be
made explicit. Let's see:

from sets import Set
genres = {
    "Comedy": Set(["t1", "t2", "t3"]),
    "Suspense": Set(["t2", "t4", "t5"])
}

def inGenre(title, titlesInGenre):
    return title in titlesInGenre

def getGenres(title, genres):
    return [name for name, titles in genres.iteritems() if inGenre(title,
titles)]

allTitles = Set()
for ts in genres.values():
    allTitles |= ts
allTitles.add("t0")

for title in allTitles:
    print title, "is in genres:", ", ".join(getGenres(title, genres))
print

if inGenre("t1", genres["Comedy"]):
    print "t1 is a comedy"

Hey, all functions have nice arguments in/return value out interfaces and
all binding woes have suddenly vanished :-)
More seriously, Python's binding concept is simple enough that you will soon
overcome that frustration.
 
Peter
        




More information about the Python-list mailing list