How Much Typing Should I Use in Python?

December 12, 2025 7 answers
Asked by CleverCoder42
After taking a break from Python while primarily coding in TypeScript and Rust, I'm finding myself struggling with how to express certain typing concepts in Python. For example, I want to indicate that an argument can be anything as long as it's `hashable` or demonstrate that a method is generic in its argument and return type. Am I overcomplicating things? Is this approach effective: if not hasattr(arg, "__hash__"): raise ValueError("argument needs to be hashable")? I think I could solve my hashable issue with `TypeVar("T", bound=typing.Hashable)`, but I'm curious about the overall typing philosophy in Python under these circumstances.

Answers

ProtoFanatic
I highly recommend looking into protocols; they can simplify your type annotations a lot!
Reply to this answer
TypeScribe99
Check out the `Protocol`s in the `typing` library. They help you with duck typing, which can make things more flexible without forcing explicit types. Itโ€™s a pretty neat way to handle typing without strict constraints.
Reply to this answer
CodeNinja123
There's actually a built-in Hashable type in the standard library. You can find it in the collections.abc module. For generics, Python definitely supports them in functions, so you could look into how that works to clarify your method's typing.
Reply to this answer
HelpfulHacker
Protocols are incredibly useful. Don't overlook them! If you want to explore more, definitely check out Pydantic for easier data validation and settings management!
Reply to this answer
PythonicGuru
Using `Protocol`s is definitely the way to go. The generics feature got a great upgrade in Python 3.12, so you might enjoy the new inline syntax. I believe that striving for a typing level similar to TypeScript can be beneficial, although TypeScriptโ€™s system has its strengths too.
Reply to this answer
RustyPythonFan
I stumbled upon an interesting article recently that dives into writing Python in a Rust-style, which might offer some fresh perspectives for you. Hereโ€™s the link: kobzol.github.io/rust/python/2023/05/20/writing-python-like-its-rust.html
Reply to this answer
TypistDev
I'd suggest using the abstract base classes from collections.abc. Many Python programmers get caught up in how typing works in statically typed languages and try to apply that to Python, which can lead to confusion. Just stick with TypedDicts, custom classes, and standard ABCs for typing your function inputs.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions