background preloader

Understanding Python's "with" statement

Understanding Python's "with" statement
Fredrik Lundh | October 2006 | Originally posted to online.effbot.org Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code: set things up try: do something finally: tear things down Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) This wasn’t very difficult, was it?

HowTo/Sorting Original version by Andrew Dalke with a major update by Raymond Hettinger Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here. Sorting Basics A simple ascending sort is very easy -- just call the sorted() function. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] You can also use the list.sort() method of a list. >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] Another difference is that the list.sort() method is only defined for lists. Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons. For example, here's a case-insensitive string comparison: The same technique works for objects with named attributes.

5.3. Defining Classes Python is fully object-oriented: you can define your own classes, inherit from your own or built-in classes, and instantiate the classes you've defined. Defining a class in Python is simple. As with functions, there is no separate interface definition. Just define the class and start coding. A Python class starts with the reserved word class, followed by the class name. Example 5.3. class Loaf: pass Of course, realistically, most classes will be inherited from other classes, and they will define their own class methods and attributes. Example 5.4. from UserDict import UserDict class FileInfo(UserDict): Python supports multiple inheritance. 5.3.1. This example shows the initialization of the FileInfo class using the __init__ method. Example 5.5. class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): 5.3.2. When defining your class methods, you must explicitly list self as the first argument for each method, including __init__. Whew.

Understanding Python Iterables and Iterators | Shut Up and Ship Decorators have been in Python since version 2.4. They are the lines that start with @ symbol just before a function or a class definition. Probably you encountered them when you defined class methods, properties etc. Or perhaps you encountered them in a web framework like Django and used them to magically add login requirements for certain pages by adding a @login_required line before your view function. Decorator formalities First let us deal with the formalities like definition, syntax, etc. Here is the template of a decorator without arguments. @decoratordef F(arg): pass # is same asdef F(arg): passF = decorator(f) And here is a decorator with arguments. @decorator(n)def F(arg): pass # is same asdef F(arg): passF = decorator(n)(F) As you can see, strictly speaking we don’t need the decorator syntax. Writing our own decorators Here are a couple of functions in our module. def simpleinterest(n, p, r): return n*p*r/100.0 def compoundinterest(n, p, r): return p*(1+r/100.0)**n-p It works!

Charming Python: Iterators and simple generators Welcome to the world of exotic flow control. With Python 2.2 (now in its third alpha release -- see Resources later in this article), programmers will get some new options for making programs tick that were not available -- or at least not as convenient -- in earlier Python versions. While what Python 2.2 gives us is not quite as mind-melting as the full continuations and microthreads that are possible in Stackless Python, generators and iterators do something a bit different from traditional functions and classes. Let's consider iterators first, since they are simpler to understand. A generator is a little more complicated and general. In some ways, a generator is like the closures which were discussed in previous installments of this column discussing functional programming (see Resources). Fortunately, using a generator is much less work than understanding all the conceptual issues of program flow and state. Taking a random walk Utilizing this function is as simple as: Back to top

Related: