Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python assertion style

Tags:

python

styles

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?

like image 864
Philip Massey Avatar asked Dec 20 '22 03:12

Philip Massey


1 Answers

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.

like image 53
Jim Garrison Avatar answered Dec 22 '22 17:12

Jim Garrison