Is there any guarantee that Python's non-callable classes will not be called?

If so, can you suggest a better way than lower? Please clarify / justify.

class X:
    ...

if __name__ == '__main__':
    # TODO: Should we bother doing this?
    errorMessage = 'This class is not meant to have a main method. Do not execute directly.'
    print(errorMessage)
    raise Error(errorMessage)
+3
source share
4 answers

I would not do that.

Here's why: python -i scriptname.pyyou can use to load the script and go to the interactive console post script. This way you get all the specific functions that you can then manipulate / test as you wish.

In this case, you will receive an error message.

+3
source

A common pattern is to place unit tests for a Python module inside the module body. For instance:

if __name__ == "__main__":
    run_unit_tests()

, , . script, Python .

+3

, . , , ,

+2
source

1) No. If something cannot be called, it will still throw an exception.

2) The design if __name__ == '__main__'refers to the module , not to the class. The "call" of the class creates an instance of the class. You also do not call modules; you either import or run them.

Please be careful with your terminology. When you correctly understand the concepts, the answers to these questions become obvious.

+1
source

Source: https://habr.com/ru/post/1778637/


All Articles