Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading