开发者

Is it worth to ensure that non-callable Python classes do not get called?

If yes, can you suggest a better way than below? Please elaborate/justify.

class X:
    ...

if __name__ == '__main__':
    # TODO: Should we bother doing this?
  开发者_Go百科  errorMessage = 'This class is not meant to have a main method. Do not execute directly.'
    print(errorMessage)
    raise Error(errorMessage)


I would not do this.

Here's why: python -i scriptname.py can be used to load in the script and drop to the interactive console post running of the script. So what you then get is all the defined functions, which you can then manipulate / test as you see fit.

Your way, you'd get an error doing this.


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

if __name__ == "__main__":
    run_unit_tests()

However, if you're not doing this, I wouldn't even bother adding any module body code. If executed as a script, a Python module with no body code will do nothing.


No, not worth it. After all, if there are no top level function calls, the code won't do anything,


1) No. If something "can't be called", it will raise an exception anyway.

2) The if __name__ == '__main__' construct refers to the module, not the class. "Calling" a class creates an instance of the class. You don't "call" modules, either; you either import or run them.

Please be more careful with your terminology. When you understand the concepts properly, the answers to these sorts of questions become obvious.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜