Python - Using Code with __name__ check


We could split the test code off into a separate file.

But it's more convenient to code tests in the same file.

We can add the test statements at the bottom only when the file is run for testing, not when the file is imported.

By using module __name__ check, we can add self-test code:


# Allow this file to be imported as well as run/tested 
class Person: 
   def __init__(self, name, job=None, pay=0): = name # from w ww  .  java  2s .c  om
       self.job  = job  = pay 

if __name__ == '__main__':                  # When run for testing only 
   # self-test code 
   bob = Person('Bob Smith') 
   sue = Person('Sue Jones', job='dev', pay=100000) 


We get exactly the behavior we're after-running the file as a top-level script tests it because its __name__ is __main__.

importing as a library of classes later does not run the testing code:

When imported, the file now defines the class, but does not use it.

Related Topic