[Tutor] Should I use type hints for all new code?

Simon Connah simon.n.connah at protonmail.com
Fri Aug 25 13:33:20 EDT 2023






------- Original Message -------
On Friday, August 25th, 2023 at 18:25, ThreeBlindQuarks <threesomequarks at proton.me> wrote:


> 

> 

> 

> Simon,
> 

> People with more experience using these features may have better answers but note how late these features were added to python even though they were available for decades in languages that not only had the features but required them!
> 

> At this point, python does not require you to tell it what types things are and so on and that is considered by many to be a good thing and especially as it allows the same piece of code to work on many things interchangeably.
> 

> Having a stronger system might allow for better code to be generated when COMPILED but Python is generally interpreted. It may not be much of a performance hit to have the interpreter IGNORE the hints but clearly it is extra work to read through bigger files and far easier to generate errors if typed in badly.
> 

> For now, the real purpose of the extra code is to allow programs like linters to check for additional possible problems with the code.
> 

> Of course, it can be quite helpful to tell others using your code what to expect but realistically, you could just as easily explain everything you want in documentation or as comments alongside the code that are also even easier to ignore.
> 

> But as the feature is there, I suspect it may be good form to use it in SOME CASES and not others. I mean if the code used requires character strings and does not handle numbers, you could make that explicit. But if your code is required to handle dozens of types then creating some notation that explicitly specifies the allowed types in the code may be more trouble than it is worth, and yet more if later someone wants to extend your code to handle additional things.
> 

> One consideration in a dynamic language like Python is that no matter what you specify, something different may still be passed along at runtime. Those types of errors can be caught, with some expense, by having a function do various kinds of validation before using the arguments passed to it, or catching exceptions.
> 

> Who is your "audience" for looking at or using your code? If in a classroom with an instructor teaching you how to use the feature, then of course you should do what they want. If in a company that demands it and builds lots of extra time in to do it, fine. But if you have a deadline that is already hard to meet, why bother?


I see what you are saying. I'm mainly using Python with Django. It is just me on my own building this site so I was curious if there were any conventions.

Thank you for the useful post!

Simon.


More information about the Tutor mailing list