-2

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?

  • You will go crazy trying to test a huge codebase like this, thus unit tests are used instead. Plus, tests are almost always put in separate files. – Filip Müller Aug 09 '22 at 09:15
  • 1
    Check out the built-in [unittest module](https://docs.python.org/3/library/unittest.html) – Filip Müller Aug 09 '22 at 09:19
  • This doesn't look pythonic, nor aligned to any software engineering practices. I'd suggest to try out some testing framework. As mentioned above – unittest, or my personal favourite [pytest](https://docs.pytest.org/en/7.1.x/) are nice options. – Max Skoryk Aug 09 '22 at 09:22

2 Answers2

0

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).

-1

Yes, it's pythonic because it's done in python. I would suggest you look at pytest but python is for beginners and everyone does thing their way.

F B I
  • 11
  • 2