How Much Typing Should I Use in Python?

0
33
Asked By CleverCoder42 On

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

Answered By TypistDev On

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.

Answered By RustyPythonFan On

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

Answered By PythonicGuru On

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.

Answered By HelpfulHacker On

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!

Answered By CodeNinja123 On

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.

Answered By TypeScribe99 On

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.

Answered By ProtoFanatic On

I highly recommend looking into protocols; they can simplify your type annotations a lot!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.