Python - Using Code with __name__ check

Introduction

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:

Demo

# Allow this file to be imported as well as run/tested 
class Person: 
   def __init__(self, name, job=None, pay=0): 
       self.name = name # www  . ja  va 2  s  . com
       self.job  = job 
       self.pay  = pay 

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

Result

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

importing person.py 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