2 ms·
I'm not very familiar with Python type checkers, so what follows may be completely off base. > The reason is because an exception is a runtime check. It caught
by tzs 5y ago
I'm not very familiar with Python type checkers, so what follows may be completely off base.
> The reason is because an exception is a runtime check. It caught an error that is hidden until runtime. The better way is to encode this logic into a static type checking system so this error isn't even permitted to run
But in
def div(x: Int, y: Int) -> Optional[Int]:
return x // y if y != 0 else None
don't you have a runtime check? It has to do a runtime check of the value of y in order to decide whether or not to return None?
I don't see how this is encoding the logic of dealing with divide by zero into the type system or permitting the error to run. I'd expect that to deal with it in the type system to not prevent it at runtime would require y to be a type that does not allow 0 (does Python's type annotations allow constrained integers?).
Handling it by returning None means the caller has to deal with None. If it deals with it by just return None too, then its caller needs to deal with it do. If whatever code finally really deals with it instead of just passing it upwards is farther up than div's caller or maybe div's caller's caller it seems like what you've ended up with is something that is less clear than exceptions and requires more runtime work.
For those cases where the return None approach is better than using an exception, can you get rid of the runtime check for y being non-zero with something like
def div(x: Int, y: Int) -> Optional[Int]:
try:
return x // y
except ZeroDivisionError:
return None
or do exceptions in Python occur sufficient overhead when not taken to make explicitly checking y win?
- hermitdev 5y agoPython, historically, has not had zero-overhead exceptions. There is a runtime cost associated with a try block. 3.11 will be adding zero-overhead exceptions, though, per https://bugs.python.org/issue40222 https://bugs.python.org/issue40222.
- deltaonefour 5y agoIt encodes it into the type system at the function signature level. Optional[Int] is an Int with a None, so if you pass this type into f(x: Int) you get a type error because f(x: Int) is a function that deals with Ints, not Optional[Int]. So you get a degree of safety here. As I mentioned this safety does not usually extend to the function definition. I stated that it can though (and it is in haskell and rust), and this is usually done through a feature called pattern matching. Pattern matching is available in python 3.10 but I'm not sure whether exhaustive type checking on pattern matching by external type checkers is available yet.