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.

206 CHAPTER 10 ■ BATTERIES INCLUDED<br />

WHY BOTHER?<br />

Why would you want to do this, you may wonder. Why not just define everything in your main program? The<br />

primary reason is code reuse. If you put your code in a module, you can use it in more than one of your programs,<br />

which means that if you write a good client database and put it in a module called clientdb, you can use it<br />

both when billing, when sending out spam (though I hope you won’t), and in any program that needs access<br />

to your client data. If you hadn’t put this in a separate module, you would have to rewrite the code in each one<br />

of these programs. So, remember: To make your code reusable, make it modular! (And, yes, this is definitely<br />

related to abstraction.)<br />

if __name__ == '__main__'<br />

Modules are used to define things such as functions and classes, but every once in a while<br />

(quite often, actually), it is useful to add some test code to a module that checks whether things<br />

work as they should. For example, if you wanted to make sure that the hello function worked,<br />

you might rewrite the module hello2 into a new one, hello3, defined in Listing 10-3.<br />

Listing 10-3. A Simple Module with Some Problematic Test Code<br />

# hello3.py<br />

def hello():<br />

print "Hello, world!"<br />

# A test:<br />

hello()<br />

This seems reasonable—if you run this as a normal program, you will see that it works.<br />

However, if you import it as a module, to use the hello function in another program, the test<br />

code is executed, as in the first hello module in this chapter:<br />

>>> import hello3<br />

Hello, world!<br />

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

Hello, world!<br />

This is not what you want. The key to avoiding it is “telling” the module whether it’s being<br />

run as a program on its own, or being imported into another program. To do that, you need the<br />

variable __name__:<br />

>>> __name__<br />

'__main__'<br />

>>> hello3.__name__<br />

'hello3'<br />

As you can see, in the “main program” (including the interactive prompt of the interpreter),<br />

the variable __name__ has the value '__main__', while in an imported module, it is set to the<br />

name of that module. Therefore, you can make your module’s test code more well behaved by<br />

putting in an if statement, as shown in Listing 10-4.

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

Saved successfully!

Ooh no, something went wrong!