Hamish Grubijan
Hamish Grubijan

Reputation: 10830

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?
    errorMessage = 'This class is not meant to have a main method. Do not execute directly.'
    print(errorMessage)
    raise Error(errorMessage)

Upvotes: 3

Views: 349

Answers (4)

user257111
user257111

Reputation:

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.

Upvotes: 3

Karl Knechtel
Karl Knechtel

Reputation: 61615

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.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993941

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.

Upvotes: 3

Tyler Eaves
Tyler Eaves

Reputation: 13131

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

Upvotes: 2

Related Questions