4 ms·
Question. The idea here is to introduce a type declaring what the requirements are of the input arguments, right? The article's example: class MeasurementL
by radarsat1 5y ago
Question. The idea here is to introduce a type declaring what the requirements are of the input arguments, right? The article's example:
class MeasurementLike(Protocol):
timestamp: datetime
declares that the object needs a field called timestamp. This is a contract that ensures the following line of code can work:
window_upper_bound = measurements[0].timestamp + window_size
The benefit being promoted by the article here, which I agree with, is that you only need to declare what the actual code requires and not name the full type of the expected input.
So, for me this raises the following: why can't this be done automatically? I can look at the code directly and see that measurements is a list with items that require a field called timestamp. Why is it necessary to write a bunch more code to tell this to a linter, when it's directly inferable from the code itself?
I can see directly that measurements must contain objects with timestamp, and that timestamp must be some object that can be added to whatever window_size is.
If it's entirely possible to get this information from the code, I don't really understand why it's necessary to burden the programmer with type hinting at all. It seems like the job for a type inference engine.
If I have to repeat a bunch of information that the compiler/(interpreter/linter..) should be able to figure out, as far as I can tell all it adds is (1) more work to do and (2) more opportunities to make mistakes. The idea of writing it all out explicitly is often celebrated as some kind of assurance of correctness; but you often figure out the types after, or in tandem, with writing the code. So it effectively is just like a "check", like those systems that make you type your password twice to make sure you didn't mistype it. Sure, it serves a purpose in the moment, but is it necessary to add maintenance burden, forever, to your code base for something that is totally redundant?
- joconde 5y agoDeclaring the types manually ensures that you don’t change the interface by accident. If I start using an attribute of an argument that wasn’t required before, I’ll get an error from the linter that will prevent me from breaking user code.