Search code examples
pythoncoding-styleidioms

Is it pythonic to use the '__main__' mechanism to test the module?


Suppose we have the following module:

# my_module.py

def my_sum(a, b):
    return a + b + 1

if __name__ == '__main__':
    s = my_sum(2, 3)
    print(s)

How bad / good / pythonic is it to test my modules or parts of them like that?

EDIT: I'm not saying or asking whether everything should be tested like that. What I mean is, if I am lazy and the module is not critical, would it be an idiomatic way to get things done quickly?


Solution

  • How about this one? The official docs state:

    This [adding the if __name__ == '__main__': ... block] is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).