12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Mixed Usage Modes: _ _name_ _ and _ _main_ _Here’s a special module-related trick that lets you import a file as a module, and runit as a standalone program. Each module has a built-in attribute called _ _name_ _,which <strong>Python</strong> sets automatically as follows:• If the file is being run as a top-level program file, _ _name_ _ is set to the string"_ _main_ _" when it starts.• If the file is being imported, _ _name_ _ is instead set to the module’s name asknown by its clients.The upshot is that a module can test its own _ _name_ _ to determine whether it’sbeing run or imported. For example, suppose we create the following module file,named runme.py, to export a single function called tester:def tester( ):print "It's Christmas in Heaven..."if __name__ == '_ _main_ _':tester( )# Only when run# Not when importedThis module defines a function for clients to import and use as usual:% python>>> import runme>>> runme.tester( )It's Christmas in Heaven...But, the module also includes code at the bottom that is set up to call the functionwhen this file is run as a program:% python runme.pyIt's Christmas in Heaven...Perhaps the most common place you’ll see the _ _name_ _ test applied is for self-testcode. In short, you can package code that tests a module’s exports in the moduleitself by wrapping it in a _ _name_ _ test at the bottom of the file. This way, you canuse the file in clients by importing it, and test its logic by running it from the systemshell, or via another launching scheme. In practice, self-test code at the bottom of afile under the _ _name_ _ test is probably the most common and simplest unit-testingprotocol in <strong>Python</strong>. (Chapter 29 will discuss other commonly used options for testing<strong>Python</strong> code—as you’ll see, the unittest and doctest standard library modulesprovide more advanced testing tools.)The _ _name_ _ trick is also commonly used when writing files that can be used bothas command-line utilities, and as tool libraries. For instance, suppose you write a filefinder script in <strong>Python</strong>. You can get more mileage out of your code if you package itin functions, and add a _ _name_ _ test in the file to automatically call those functionswhen the file is run standalone. That way, the script’s code becomes reusable inother programs.428 | Chapter 21: Advanced Module Topics

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

Saved successfully!

Ooh no, something went wrong!