Python en:More

Introduction
So far we have covered majority of the various aspects of Python that you will use. In this chapter, we will cover some more aspects that will make our knowledge of Python more well-rounded.

Passing tuples around
Ever wished you could return two different values from a function? You can. All you have to do is use a tuple.

Notice that the usage of a, b = &lt;some expression&gt; interprets the result of the expression as a tuple with two values.

If you want to interpret the results as (a, &lt;everything else&gt;), then you just need to star it just like you would in function parameters:

This also means the fastest way to swap two variables in Python is:

Special Methods
There are certain methods such as the __init__ and __del__ methods which have special significance in classes.

Special methods are used to mimic certain behaviors of built-in types. For example, if you want to use the x[key] indexing operation for your class (just like you use it for lists and tuples), then all you have to do is implement the __getitem__ method and your job is done. If you think about it, this is what Python does for the list class itself!

Some useful special methods are listed in the following table. If you want to know about all the special methods, see the manual.

Single Statement Blocks
We have seen that each block of statements is set apart from the rest by its own indentation level. Well, there is one caveat. If your block of statements contains only one single statement, then you can specify it on the same line of, say, a conditional statement or looping statement. The following example should make this clear:

Notice that the single statement is used in-place and not as a separate block. Although, you can use this for making your program smaller, I strongly recommend avoiding this short-cut method, except for error checking, mainly because it will be much easier to add an extra statement if you are using proper indentation.

Lambda Forms
A lambda statement is used to create new function objects and then return them at runtime.

Output:

$ python lambda.py   wordword 10

How It Works:

Here, we use a function make_repeater</tt> to create new function objects at runtime and return it. A lambda</tt> statement is used to create the function object. Essentially, the lambda</tt> takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function. Note that even a print</tt> statement cannot be used inside a lambda form, only expressions.


 * TODO
 * Can we do a list.sort</tt> by providing a compare function created using lambda</tt>?

List Comprehension
List comprehensions are used to derive a new list from an existing list. Suppose you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 only when the number itself is greater than 2. List comprehensions are ideal for such situations.

Output:

$ python list_comprehension.py   [6, 8]

How It Works:

Here, we derive a new list by specifying the manipulation to be done (2*i</tt>) when some condition is satisfied (if i &gt; 2</tt>). Note that the original list remains unmodified.

The advantage of using list comprehensions is that it reduces the amount of boilerplate code required when we use loops to process each element of a list and store it in a new list.

Receiving Tuples and Lists in Functions
There is a special way of receiving parameters to a function as a tuple or a dictionary using the *</tt> or **</tt> prefix respectively. This is useful when taking variable number of arguments in the function.

Because we have a *</tt> prefix on the args</tt> variable, all extra arguments passed to the function are stored in args</tt> as a tuple. If a **</tt> prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.

exec and eval
The exec</tt> function is used to execute Python statements which are stored in a string or file, as opposed to written in the program itself. For example, we can generate a string containing Python code at runtime and then execute these statements using the exec</tt> statement:

Similarly, the <tt>eval</tt> function is used to evaluate valid Python expressions which are stored in a string. A simple example is shown below.

The assert statement
The <tt>assert</tt> statement is used to assert that something is true. For example, if you are very sure that you will have at least one element in a list you are using and want to check this, and raise an error if it is not true, then <tt>assert</tt> statement is ideal in this situation. When the assert statement fails, an <tt>AssertionError</tt> is raised.

The <tt>assert</tt> statement should be used judiciously. Most of the time, it is better to catch exceptions, either handle the problem or display an error message to the user and then quit.

The repr function
The <tt>repr</tt> function is used to obtain a canonical string representation of the object. The interesting part is that you will have <tt>eval(repr(object)) == object</tt> most of the time.

Basically, the <tt>repr</tt> function is used to obtain a printable representation of the object. You can control what your classes return for the <tt>repr</tt> function by defining the <tt>__repr__</tt> method in your class.

Summary
We have covered some more features of Python in this chapter and yet we haven't covered all the features of Python. However, at this stage, we have covered most of what you are ever going to use in practice. This is sufficient for you to get started with whatever programs you are going to create.

Next, we will discuss how to explore Python further.

Previous Next