23
submitted 7 months ago* (last edited 7 months ago) by wasabi@feddit.de to c/python@programming.dev

I often find myself defining function args with list[SomeClass] type and think "do I really care that it's a list? No, tuple or Generator is fine, too". I then tend to use Iterable[SomeClass] or Collection[SomeClass]. But when it comes to str, I really don't like that solution, because if you have this function:

def foo(bar: Collection[str]) -> None:
    pass

Then calling foo("hello") is fine, too, because "hello" is a collection of strings with length 1, which would not be fine if I just used list[str] in the first place. What would you do in a situation like this?

you are viewing a single comment's thread
view the rest of the comments
[-] sloppy_diffuser@sh.itjust.works 1 points 7 months ago

Look at the official docs. There is a table part way down stating which methods are available for each. I pick the one closest to how I use it. So if I'm not mutating I'll use Sequence over List to inform the caller I'm treating as immutable and to safe guard myself from mutating it in my implementation via static type analysis.

https://docs.python.org/3/library/collections.abc.html

[-] wasabi@feddit.de 2 points 7 months ago

str matches most of these contracts, though, requiring additional checks if a str was passed or one of these collections containing strings.

this post was submitted on 01 Feb 2024
23 points (100.0% liked)

Python

6187 readers
10 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS