mypy – How to mark line as unreachable

Question:

I’ve got a function of the form:

def get_new_file(prefix: str) -> pathlib.Path:
    for i in itertools.count(0):
        p = pathlib.Path(f'{prefix}_{i}')
        if not p.is_file():
            return p
    # This line is unreachable.

mypy understandably complains that the function is missing a return statement. Is there a way to mark a line so as to inform mypy that the line should be considered unreachable?

Asked By: Daniel Walker

||

Answers:

This was raised as an issue. The recommended solution is assert False.

def get_new_file(prefix: str) -> pathlib.Path:
    for i in itertools.count(0):
        p = pathlib.Path(f'{prefix}_{i}')
        if not p.is_file():
            return p
    assert False
Answered By: LeopardShark

once again this is a typical issue where keeping things simple should apply. Mypy obviously does not know where the loops ends, so its warning you about it in advance as the function’s endofline statement does not have a return statement.

A simple approach is to break the loop and return the last value of the pathlib.Path which was last set. Here is an example.

def get_new_file(prefix: str) -> pathlib.Path:
    p : Optional[pathlib.Path] = None 
    for i in itertools.count(0):
        p = pathlib.Path(f'{prefix}_{i}')
        if not p.is_file():
            break
    
    return p 

if you restructure the above code snippet, mypy will not raise the errors again.

Answered By: Jeff C

Mypy is not wrong, you should not mark that line as unreachable but raise an error, even if you are sure that you won’t ever hit that line it’s a good coding practice and you can save yourself some time debugging later on

def get_new_file(prefix: str) -> pathlib.Path:
    for i in itertools.count(0):
        p = pathlib.Path(f'{prefix}_{i}')
        if not p.is_file():
            return p
    raise Exception # pick a meaningful exception
Answered By: Axeltherabbit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.