return -1
Python has a different error handling method than C. If there is a problem with the data provided, simply allow the AssertionError to pass or raise a TypeError or ValueError with a special error message. A custom error message with assert statement is the simplest:
assert port_number > 0, "Invalid port number"
The fact that assert statements may be disabled at compile time may be a point to consider if you want to use assert statements in your situation. Itβs not common practice to use assert statements to validate user input for your functions, but only for internal sanity checks. On the other hand, the boundaries between sanity checks and validation are not defined. Examples of parts of your code without claims:
if port_number <= 0: raise ValueError('Invalid port number') if not isinstance(port_number, (int, float)): raise TypeError('Port number must be some kind of number')
Personally, I use assert statements to verify data that, if invalid, will fail sooner or later in any case (see "duck print"). I also actively use assertions during development to verify performance - I check my data, as it would in a statically typed language. I use only such statements if I strongly doubt the stability and reliability of my own code.
Next line:
assert self.handle == None
If I remember correctly, PEP8 says you should write assert self.handle is None . At least it was approved by people who are smarter than me.
assert isinstance(port_number, int) or isinstance(port_number, float)
If you really need it, it can be written as isinstance(port_number, (int, float)) . But it turns out you wonβt do it. You donβt care if anyone passes a numerical primitive type or some kind of makeshift class that overloads all comparison operators.
Perhaps one thing you can do is try to pass the port to an integer and see if it can be used or not:
try: port_number = int(port_number) except ValueError: raise ValueError("Invalid port number")
And also in this case, you can simply skip ValueError , the message will be less informative for beginners.