News for hackers. Stuff that matters.
Re:Python Type Hints by echelon on Sunday December 29, 2019 @06:18AM (#21905344)
The perfect level for types is at the function or interface level.

I'm not a PL theory guy (so correct me if I'm theoretically wrong), but it turns out you can usually infer types for everything as long as methods and functions are annotated. It only breaks down in the case of complicated generics or heterogeneous containers, and in those cases often only when there are chained method calls that prevent inference of the intermediate calls.

Typing at the function level is extremely useful for all languages, both statically and dynamically typed. Python, TypeScript, Rust, Java, etc. all benefit.

A broad class of errors are caused by passing the wrong types into functions. In scripting languages, these creep in due to mistakes or refactors. Types on functions can prevent this. It also helps you avoid writing tests or precondition checks for the wrong type of input.

Speaking of refactors, having type information on function calls lets you do codebase-wide function signature changing, method renaming, etc. with the assurance you won't break your code or miss any calls. It's a killer feature.

Even if you gained nothing from the practice, you always want to know what you're required to pass a function.

    def resize_image(image, width, height, strategy):
        pass
What do any of those parameters mean? Do you want to rely on documentation? That can get out of sync, especially during refactors or in multi-engineer projects.

Types on functions are the way to go. Once you try it, you'll never look back.

There are no comments on this comment yet.