Python
  Home arrow Python arrow Page 2 - Nested Functions in Python
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

Nested Functions in Python
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2008-11-06


    Table of Contents:
  • Nested Functions in Python
  • Nested functions and nested scopes
  • Generators
  • Generators in Python 2.5

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Nested Functions in Python - Nested functions and nested scopes
    ( Page 2 of 4 )

    A def statement within a function body defines a nested function, and the function whose body includes the def is known as an outer function to the nested one. Code in a nested function's body may access (but not rebind) local variables of an outer function, also known as free variables of the nested function.

    The simplest way to let a nested function access a value is often not to rely on nested scopes, but rather to explicitly pass that value as one of the function's arguments. If necessary, the argument's value can be bound when the nested function is defined by using the value as the default for an optional argument. For example:

      def percent1(a, b, c):
         
    def pc(x, total=a+b+c): return (x*100.0) / total
         
    print "Percentages are:", pc(a), pc(b), pc(c)

    Here's the same functionality using nested scopes:

      def percent2(a, b, c):
         
    def pc(x): return (x*100.0) / (a+b+c)
          print "Percentages are:", pc(a), pc(b), pc(c)

    In this specific case, percent1 has a tiny advantage: the computation of a+b+c  happens only once, while percent2's inner function pc repeats the computation three times. However, if the outer function rebinds its local variables between calls to the nested function, repeating the computation can be necessary. It's therefore advisable to be aware of both approaches, and choose the most appropriate one case by case.

    A nested function that accesses values from outer local variables is also known as a closure. The following example shows how to build a closure:

      def make_adder(augend):
          def add(addend):
              return addend+augend
          return add

    Closures are an exception to the general rule that the object-oriented mechanisms covered in Chapter 5 are the best way to bundle together data and code. When you need specifically to construct callable objects, with some parameters fixed at object construction time, closures can be simpler and more effective than classes. For example, the result of make_adder(7) is a function that accepts a single argument and adds 7 to that argument. An outer function that returns a closure is a "factory" for members of a family of functions distinguished by some parameters, such as the value of argument augend  in the previous example, and may often help you avoid code duplication.

    lambda Expressions

    If a function body is a single return expression statement, you may choose to replace the function with the special lambda expression form:

      lambda parameters: expression

    A lambda expression is the anonymous equivalent of a normal function whose body is a single return statement. Note that the lambda syntax does not use the return keyword. You can use a lambda expression wherever you could use a reference to a function. lambda can sometimes be handy when you want to use a simple function as an argument or return value. Here's an example that uses a lambda expression as an argument to the built-in filter function (covered in filter on page 161):

      aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      low = 3
      high = 7
      filter(lambda x, l=low,
    h=high: h>x>l, aList)         # returns: [4, 5, 6]

    As an alternative, you can always use a local def statement that gives the function object a name. You can then use this name as the argument or return value. Here's the same filter example using a local def statement:

      aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      low = 3
      high = 7
      def within_bounds(value, l=low, h=high):
          return h>value>l
      filter(within_bounds, aList)       # returns: [4, 5, 6]

    While lambda can occasionally be useful, many Python users prefer def, which is more general, and may make your code more readable if you choose a reasonable name for the function.



     
     
    >>> More Python Articles          >>> More By O'Reilly Media
     

       

    PYTHON ARTICLES

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek