59 ms·
Of course it takes longer to read and comprehend the method signature when there are types in it, since it makes the method signature longer. But by the time I
by rcthompson 4y ago
Of course it takes longer to read and comprehend the method signature when there are types in it, since it makes the method signature longer. But by the time I make it to the end of the signature, before I've even taken a look at the function body, the types have already given me important information (assuming this is a codebase where MyPy types are enforced) that will make reading the code much easier, because I don't have the mental overhead of needing to infer the types of half a dozen arguments and the return type while reading the code. And often, the type signature is the information I was looking for anyway, and as long as I trust the function to be implemented correctly, I can skip reading the body entirely.
For instance, if I see a function signature like "def parse_int(x: str) -> int", I can probably guess what the function will do. It might be parsing the entire string as an integer, or it might be parsing the first integer it can find within that string, but that type signature by itself eliminates a lot of weird things that could plausibly fall within the purview of a function named "parse_int". It can't return an iterable over all integers parsed from the string; it can't conditionally return an int if there's a single integer and a list of ints if there's more than one; it only accepts a decoded string (i.e. not bytes or any other string representation); it can't take a list of strings and return the first integer it finds; it can't return a string representation of the parsed integer; it can't return None if parsing fails (meaning it will likely throw an exception instead); and so on. Thus, even if I need to read the function body to see exactly what it's doing, I go into it thinking "in what specific way is this function parsing a single integer from a single string?" rather than "I wonder what this function does".