Closures / Blocks in Python

Jason tenax.raccoon at gmail.com
Tue Jul 24 17:32:26 CEST 2007


On Jul 24, 8:58 am, treble54 <trebl... at gmail.com> wrote:
> Does anyone know a way to use closures or blocks in python like those
> used in Ruby? Particularly those used in the { } braces.

Python isn't Ruby.  Python has a lambda function for creating
anonymous functions, but many of the common use cases expired with the
introduction of iterators and comprehensions.  Python's functions are
first class objects, and can be passed around, bound to names, and
used like any other object.  (I don't know whether Ruby's functions
are first class objects.)  Python's function objects are callable, but
so are classes (calling them creates a class instance) and some
instances (those that define the __call__ special method).

If you can't find a way of doing what you want with iterators,
comprehensions, or lambda, consider writing a little function.  Heck,
you can even nest functions in Python or pass a function as a
parameter.

For example, removing all names that start with a 'J' from a list of
names:
newListOfNames = [ name  for name in nameList  if not
name.startswith('J') ]  # List comprehension
newListOfNames = filter(lambda name: not name.startswith('J'),
nameList)      # Filter with lambda

# Explicit for-loop
newListOfNames = []
for name in nameList:
    if not name.startswith('J'):  newListOfNames.append(name)


Take a look at "http://ivan.truemesh.com/archives/000392.html" for a
comparison between some simple Ruby code and Python.  Hope this helps.

  --Jason




More information about the Python-list mailing list