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.
7 Answers
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.
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
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.
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!
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.
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.
I highly recommend looking into protocols; they can simplify your type annotations a lot!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically