6 ms·
Yep. Therefore it’s better to def twice(x: int) -> int: if not isinstance(x, int): raise TypeError("Expected x to be an int, got " + str(type(
by Ringz 3y ago
Yep. Therefore it’s better to
def twice(x: int) -> int:
if not isinstance(x, int):
raise TypeError("Expected x to be an int, got " + str(type(x)))
return x + x
- jhardy54 3y agoThis can have substantial performance implications, not to mention DX considerations.
- Ringz 3y agoOf course, this is not a good example of good, high-performance code, only an answer to the specific question... the questioner certainly also knows MyPy.
- Joker_vD 3y agoI actually don't know anything about MyPy, only that it exists. Does it run that example correctly, that is, does it print "nopenope"? Because I think it's the correct behaviour, type hints should not actually affect evaluation (well, beyond the fact that they must be names that are visible in the scopes thay're used in, obviously), altough I could be wrong. Besides, my point was that one of the reasons why languages with (sound-ish) static types manage to have better performance because they can omit all of those run-time type checks (and the supporting machinery) because they'd never fail. And if you have to put those explicit checks, then the type hints are actually entirely redundant: e.g. Erlang's JIT ignores type specs, it instead looks at the type guards in the code to generate specialized code for the function bodies.
- sgerenser 3y agoSurely this is the job for a linter or code generator (or perhaps even a hypothetical ‘checked’ mode in the interpreter itself)? Ain’t nobody got time to add manual type checks to every single function.
- Ringz 3y agoOf course not. That's what MyPy is for. It was only about the answer to exactly this question in this function.
- adhamsalama 3y agoOr use mypy.