Type hints for variable first mentions - yes/no/sometimes(when?)?
Posted by sarnobat@reddit | Python | View on Reddit | 15 comments
I'm new to python from a java background. It's so easy when you are writing new code or are reading code you wrote in the last hour (e.g. during an interview).
Reading some code I wrote last week in a Colab notebook for a class notebook using some API that I'm learning (e.g. Word2Vec), it's not so easy. I don't know what operations I can perform on this variable I added but didn't name with enough information to trivially determine its type.
Java is so explicit with type declarations it makes you cry, but I'm seeing the dark side of dynamic typing.
One possible solution is to use type hints anywhere the type info is welcome (subjective I know). But is there any kind of best practice which maybe says that you should not do it to the point it just crowds your code?
Spatrico123@reddit
I recommend using type hints for function params and returns. In line variables are generally not needed.
I also came to python from a Java background and missed the disciplined type checking. To make up for it, I run MyPy, Pyright and Ruff linters on my code in real time. They'll highlight my code in red if my type checks are missing or inconsistent; which is exactly what I expect.
Be warned, the python runtime ignores type checking!
def foo(i: int) -> int: return "llama"
print(foo(1.23))
runs without error, because the python runtime ignores the type hints. You need an LSP or a linter to spot those errors as you type. Or run your code wrapped in typeguard to essentially automatically wrap every type checked value in an assert(isinstance()) block
ejgl001@reddit
Same. The only other place where I add them is if the type is not inferred by the IDE or clear
HolidayEmphasis4345@reddit
New code, I type everything, vars, parameters, func returns. The editor experience is worth it alone. If the code is production I will drive mypy, coverage and pylint to high 90s whenever possible when code will have a long life.
Bringing old code to this standard is very painful. Very dynamic code is painful, but understanding the pain helps.
Gnaxe@reddit
In a notebook? Pretty much never. You have the live objects. They will tell you about themselves if you ask. Use
?
orbreakpoint()
/help()
/dir()
to inspect them. IPython also has a%debug
magic.You can add assertions to document assumptions or doctests to document usage and do simple tests. You can also write Markdown cells for presentation.
In a larger project in an IDE, the type annotations become somewhat more useful. Mostly because the built-in linter will flag your type errors, but you'll also get better pop-up completions. But static typing will also tend to overcomplicate your design by encouraging a more Java-like style. I recommend that you avoid it except in trivial cases. If you ever feel like you're fighting the type checker or the typing is longer than the code, give up. I still prefer the REPL-driven design more like in a notebook, even for larger projects.
Statically typed languages don't have a lower defect rate than dynamically typed languages. That's a myth not supported by the empirical evidence. To control bugs in a large project, there is no substitute for automated tests.
Flaky-Razzmatazz-460@reddit
I’ll add that to see the type information you need to use the
inspect
moduleGnaxe@reddit
You can see an object's class using the
type()
builtin. You can check is-a relationships with theisinstance()
builtin (for instances) and theissubclass()
builtin (for classes). You can show the whole inheritance chain using.__mro__
on the class (or useinspect.getmro()
).0ntsmi0@reddit
In my opinion and experience, type hints are only necessary where the type can't be fully inferred by the type checker at the declaration point. As in, if my type checker complains that it doesn't know a type, I'll give it a type hint.
For example:
Any good IDE will just show you the type by hovering over a symbol, and this is not limited to Python.
PS.
👉
var
👈FrontAd9873@reddit
To your point about “any good IDE,” it is worth noting that OP is using a Google Colab notebook. Generally notebooks have poor support for type checking.
jaerie@reddit
If the types aren't checked properly for correctness, the value of annotations are vastly reduced anyway.
noobsc2@reddit
I dunno if I would make any comparison with `var` in Java here which only exists for convenience. Any variable declared using var is still completely explicit.
LexaAstarof@reddit
I type hint for two reasons: better IDE integration for autocompletion and inline doc (fancy way of saying I am lazy), and static check for additional peace of mind (additional ie. on top of tests).
For actually following the type of what is what in my mind, type hint is actually more of a noise than a helper.
Before type hints we had to have the discipline of writing code that speaks for itself. And no, I don't mean prefixing/suffixing variables names with shorthands for their type... Write code in a way that it expresses what it does naturally, and the types will appear from it as well.
lolcrunchy@reddit
Type hints for initial argument declarations, function signatures, and class properties are enough.
GuyOnTheInterweb@reddit
Often collections need help as well
IrrerPolterer@reddit
Whenever mypy complains.
rainyy_day@reddit
whatever mypy thinks