16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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 in<strong>to</strong> the if statement; however, by putting it in a separate test function, you can<br />

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

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

Hello, world!<br />

■Note If you write more thorough test code, it might be a good idea <strong>to</strong> 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 direc<strong>to</strong>ries (as strings)<br />

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

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

module) <strong>to</strong> 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 <strong>Python</strong> interpreter looks<br />

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

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

and you do not have administra<strong>to</strong>r permissions, you may not be able <strong>to</strong> save your module in any of the direc<strong>to</strong>ries<br />

used by <strong>Python</strong>. You will then have <strong>to</strong> skip ahead <strong>to</strong> solution number 2.

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

Saved successfully!

Ooh no, something went wrong!