I'm wondering if what I'm doing is an appropriate method of assertions. I'm trying to making something both concise and very correct for Python's style guides.
try:
assert self.port_number == 0
assert self.handle == None
assert isinstance(port_number, int) or isinstance(port_number, float)
assert port_number > 0
except AssertionError:
return -1
*body of code*
return 0
Above is an excerpt of my code that shows how I handle argument assertions. You can assume that I've covered all of the necessary assertions and the input is port_number. Is this considered good style? Is there a better way?
The assert
statement should only be used to check the internal logic of a program, never to check user input or the environment. Quoting from the last two paragraphs at http://wiki.python.org/moin/UsingAssertionsEffectively ...
Assertions should not be used to test for failure cases that can occur because of bad user input or operating system/environment failures, such as a file not being found. Instead, you should raise an exception, or print an error message, or whatever is appropriate. One important reason why assertions should only be used for self-tests of the program is that assertions can be disabled at compile time.
If Python is started with the -O option, then assertions will be stripped out and not evaluated. So if code uses assertions heavily, but is performance-critical, then there is a system for turning them off in release builds. (But don't do this unless it's really necessary. It's been scientifically proven that some bugs only show up when a customer uses the machine and we want assertions to help there too. )
With this in mind, there is virtually never a reason to catch an assertion in user code, ever, as the entire point of the assertion failing is to notify the programmer as soon as possible that there is a logic error in the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With