4 ms·
Could you do this in Python (using positive integers as an example of a type rather than even numbers)?: class N(int): def __init__(self, z: int):
by gorgoiler 3y ago
Could you do this in Python (using positive integers as an example of a type rather than even numbers)?:
class N(int):
def __init__(self, z: int):
assert z > 0
super().__init__(z)
def log2(n: N) -> float:
…
log2(N(32)) # 5.0
log2(32) # type error
log2(N(-32)) # runtime error
You are still relying on the runtime to detect errors and it’s annoying to have to cast all ints to Ns, but you at least won’t ever take the log of a negative number.
- benrutter 3y agoThat's a cool trick! Depending on your use case though it might not go far enough since the new "type" is really just an integer with an assert. It won't be picked up by static type checkers and there's nothing stopping you doing this: ``` x = N(2) x -= 10 ``` I think x still winds up being less than 0 here? Its probably easier just to add an "assert" with a friendly message at the start of the log function.