12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

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

Unit Tests with _ _name_ _In fact, we’ve already seen a prime example in this book of an instance where the_ _name_ _ check could be useful. In the section on arguments in Chapter 16, wecoded a script that computed the minimum value from the set of arguments sent in:def minmax(test, *args):res = args[0]for arg in args[1:]:if test(arg, res):res = argreturn resdef lessthan(x, y): return x < ydef grtrthan(x, y): return x > yprint minmax(lessthan, 4, 2, 1, 5, 6, 3)print minmax(grtrthan, 4, 2, 1, 5, 6, 3)# Self-test codeThis script includes self-test code at the bottom, so we can test it without having toretype everything at the interactive command line each time we run it. The problemwith the way it is currently coded, however, is that the output of the self-test call willappear every time this file is imported from another file to be used as a tool—not exactlya user-friendly feature! To improve it, we can wrap up the self-test call in a _ _name_ _check, so that it will be launched only when the file is run as a top-level script, not whenit is imported:print 'I am:', _ _name_ _def minmax(test, *args):res = args[0]for arg in args[1:]:if test(arg, res):res = argreturn resdef lessthan(x, y): return x < ydef grtrthan(x, y): return x > yif _ _name_ _ == '_ _main_ _':print minmax(lessthan, 4, 2, 1, 5, 6, 3)print minmax(grtrthan, 4, 2, 1, 5, 6, 3)# Self-test codeWe’re also printing the value of _ _name_ _ at the top here to trace its value. <strong>Python</strong>creates and assigns this usage-mode variable as soon as it starts loading a file. Whenwe run this file as a top-level script, its name is set to _ _main_ _, so its self-test codekicks in automatically:% python min.pyI am: _ _main_ _16Mixed Usage Modes: _ _name_ _ and _ _main_ _ | 429

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

Saved successfully!

Ooh no, something went wrong!