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 10 ■ BATTERIES INCLUDED 207<br />

Listing 10-4. A Module with Conditional Test Code<br />

# hello4.py<br />

def hello():<br />

print "Hello, world!"<br />

def test():<br />

hello()<br />

if __name__ == '__main__': test()<br />

If you run this as a program, the hello function is executed, whereas if you import it, it<br />

behaves like a normal module:<br />

>>> import hello4<br />

>>> hello4.hello()<br />

Hello, world!<br />

As you can see, I’ve wrapped up the test code in a function called test. I could have put the<br />

code directly into the if statement; however, by putting it in a separate test function, you can<br />

test the module even if you have imported it into another program:<br />

>>> hello4.test()<br />

Hello, world!<br />

■Note If you write more thorough test code, it might be a good idea to put it in a separate program. See<br />

Chapter 16 for more on writing tests.<br />

Making Your Modules Available<br />

In the previous examples, I have altered sys.path, which contains a list of directories (as strings)<br />

in which the interpreter should look for modules. However, you don’t want to do this in general.<br />

The ideal case would be for sys.path to contain the right directory (the one containing your<br />

module) to begin with. There are two ways of doing this:<br />

Solution 1: Putting Your Module in the Right Place<br />

Putting your module in the right place (or, rather a right place, because there may be several<br />

possibilities) is quite easy. It’s just a matter of finding out where the Python interpreter looks<br />

for modules and then putting your file there.<br />

■Note If the Python interpreter on the machine you’re working on has been installed by an administrator<br />

and you do not have administrator permissions, you may not be able to save your module in any of the directories<br />

used by Python. You will then have to skip ahead to solution number 2.

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

Saved successfully!

Ooh no, something went wrong!