04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 5 ■ CONDITIONALS, LOOPS, AND SOME OTHER STATEMENTS 83<br />

from somemodule import *<br />

The latter should only be used when you are certain that you want to import everything<br />

from the given module. But what if you have two modules each containing a function called<br />

open, for example—what do you do then? You could simply import the modules using the first<br />

form, and then use the functions as follows:<br />

module1.open(...)<br />

module2.open(...)<br />

But there is another option: You can add an as clause to the end and supply the name you<br />

want to use, either for the entire module:<br />

>>> import math as foobar<br />

>>> foobar.sqrt(4)<br />

2.0<br />

or for the given function:<br />

>>> from math import sqrt as foobar<br />

>>> foobar(4)<br />

2.0<br />

For the open functions you might use the following:<br />

from module1 import open as open1<br />

from module2 import open as open2<br />

Assignment Magic<br />

The humble assignment statement also has a few tricks up its sleeve.<br />

Sequence Unpacking<br />

You’ve seen quite a few examples of assignments, both for variables and for parts of data structures<br />

(such as positions and slices in a list, or slots in a dictionary), but there is more. You can perform<br />

several different assignments simultaneously:<br />

>>> x, y, z = 1, 2, 3<br />

>>> print x, y, z<br />

1 2 3<br />

Doesn’t sound useful? Well, you can use it to switch the contents of two (or more)<br />

variables:<br />

>>> x, y = y, x<br />

>>> print x, y, z<br />

2 1 3<br />

Actually, what I’m doing here is called “sequence unpacking”—I have a sequence of values,<br />

and I unpack it into a sequence of variables. Let me be more explicit:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!