advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 4.2/5 | Rate this item | 5 users have rated this item.
Email this articleEmail this article
 
Power Python: Do More with Less Code
Python offers some elegant constructs that enable you to write clearer, more concise code. Use these powerful language features to do more with less code. 

advertisement
hat's Power Python, you ask? It's the effective use of Python language features to get a lot of work done in fewer lines of code. The lambda, reduce, filter, map, and list comprehension constructs are some of the features that best fit this definition. This article examines each one in turn and highlights some of their strengths with simple code examples that illustrate the basic syntax and usage. It then delves into some related coding advantages that Python offers, such as the easy creation of callbacks and closures.

The built-in Python functions discussed adhere to some of the basic principles of Functional Programming (FP). While this article doesn't focus on the philosophy of FP per se, it does highlight some of the advantages of the FP style of programming, such as the emphasis on list processing, the use of functions to replace looping, the avoidance of side effects, and the reliance on functions being first class objects. By the end of the article, you should have a strong grasp of how you can use these powerful techniques to write more expressive and concise code in your projects.

Author's Note: Examples in the text assume the reader is at least an advanced beginner in Python programming.

Lambda
The lambda construct allows you to create anonymous functions on the fly. Since methods are first-class objects in Python, you can pass anonymous functions around as arguments to a method. Practically speaking, because methods are first-class objects, you can assign a method to a variable just as you would an instance of a class. (If you've got a C background, passing a method in this manner is essentially the same as a pointer to a function.) This ability to use method objects as arguments to a function makes it simple to implement callbacks.

Figure 1 illustrates the syntax and usage of the lambda.

Figure 1: Syntax and Usage of the Lambda Construct

Though the example in Figure 1 is trivial, you can see that using lambda eliminates the need for an additional if conditional block. In more complex code, consolidating conditional logic into small helper lambda functions (that you don't need to define as methods in their own right) can make code more structured and readable.

If the concept of a callback is unfamiliar to you, consider another example: the Python standard library's os.path.walk(root, function, args ) method. The walk() function uses the passed argument (args) to apply the method's function argument as the code recursively iterates through a directory tree starting at the specified root. This repeated calling out (or back) to the same function while executing the loop may be how the technique got the name callback, but don't quote me on that.

You'll find a practical implementation of the walk( ) method in a previously published DevX article I wrote Python Boosts Jar Auditor Functionality. The auditor utility highlighted in that article presents another useful Python feature as well: the ability to create closures. Objects are data bundled with behavior (methods); closures are methods bundled with some data. Python enables you to create closures by allowing methods to set initial argument values in the method definition itself (see Figure 2).

Figure 2: Create Closures in Python

In the Figure 2 snippet, Python presets the y value. This way, if a value isn't passed to the method (under some condition), the method uses the value set in the method definition. This adds great flexibility to the way methods are called. This isn't just syntactic sugar. The added expressive power, depending upon the circumstances, can simplify or reduce the coded logic required to set the argument(s) that need to be passed.

  Next Page: Map( )
Page 1: IntroductionPage 3: Reduce( )
Page 2: Map( ) 
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES