Search code examples
pythontype-hinting

How to keep linters from complaining about type hints that don't match on a technicality?


Considering the toy example:

def get_dimensions(the_string: str) -> tuple[int, int]:
    return tuple([int(_) for _ in the_string.split("x")])

I know that the_string will only ever contain on x (it's just the output of an ffprobe command), so I'm not concerned that this could return a tuple with more or less than 2 integers, but the reality is that linters like PyCharm are going to rightfully complain about the above as the type hint tuple[int, int] doesn't agree with the possible output of tuple[int,...].

What's the right thing to do here? I can adjust the last line there to use maxsplit=1, but that feels redundant, but I don't know of a way to indicate that the_string should only contain one x either. Is there a "right" way to do this? Should I just change the type hint? Is setting maxsplit=1 the preferred albeit pointlessly verbose style? Is there some way to tell the linter not to worry about this?


Solution

  • Instead of using maxsplit, you can split that line to:

    def get_dimensions(the_string: str) -> tuple[int, int]:
        first, second = the_string.split("x")
        return int(first), int(second)
    

    This could even be arguably more readable and explicit than the original and the main advantage over using maxsplit is that you will simply get an error whenever the_string will not match your assumption.