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?

  • 𝕨𝕒𝕤𝕒𝕓𝕚OP
    link
    fedilink
    25 months ago

    This + an assert seems like the way to go. I think that str should never have fulfilled these contracts in the first place and should have a .chars property that returns a list of one-character-strings. But this change would break existing code, so it is not going to happen.

    • IDK, I think strings being simple lists is less surprising than having a unique type. Most other languages model them that way, and it’s nice to be able to use regular list actions to interact with them.

      It’s really not something I’m likely to run into in practice. The only practical way I see messing this up is with untrusted inputs, but I sanitize those anyway.