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?
I’m not sure why you wouldn’t just use packing to pass in a list of some objects that you need iterate over? Isn’t it normally bad form to pass lists as arguments? I feel like I’ve read this somewhere but can’t cite it
Yes, that’s a good alternative for
Collection[str]
but not so much forIterable[str]
as you lose the lazyness of Generators.