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?

  • Troy@lemmy.ca
    link
    fedilink
    arrow-up
    4
    arrow-down
    1
    ·
    3 years ago

    Kids these days and their type hinting. Back in my day, all objects were ducks, and we liked it!

  • Gamma@beehaw.org
    link
    fedilink
    English
    arrow-up
    2
    ·
    3 years ago

    I’m rusty on my type hints because I’ve been living in lua land lately, but from ye olde PEP 20

    Explicit is better than implicit.

    I’d combine them so the hint was something like Union[Collection[str], str]

      • Gamma@beehaw.org
        link
        fedilink
        English
        arrow-up
        1
        ·
        3 years ago

        Oh, I had it backwards! I tried to mess with the hint and couldn’t find anything, maybe an assert?

        from typing import Collection
        
        def foo(bar: Collection[str]):
            assert not isinstance(bar, str)
            print(bar)
        
    • 𝕨𝕒𝕤𝕒𝕓𝕚@feddit.deOP
      link
      fedilink
      English
      arrow-up
      3
      ·
      3 years ago

      I know that Iterable and Collection aren’t the same. My point is, that if you use Iterable[str] or Collection[str] as a more flexible alternative to list[str] you no longer have any type-hinting support protecting against passing in a plain string and you could end up with a subtle bug by unexpectedly looping over ['f', 'o', 'o'] instead of ['foo'].

  • pythonoob@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    3 years ago

    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