microsoft / pylance-release

Documentation and issues for Pylance
Creative Commons Attribution 4.0 International
1.7k stars 770 forks source link

"Code is unreachable" for reachable code #6021

Closed chilipepperpizza closed 3 months ago

chilipepperpizza commented 3 months ago

Environment data

Code Snippet

def test(arg1: str = None, arg2 = False):
    if arg2:
        print('Made it this far')
        return
    elif arg1 is not None:
        print('Made it to here')
        return

    print('Made it all the way')

test()
#>>> Made it all the way

Repro Steps

  1. Have a function with a basic if-elseif statement checking argument conditions with returns.

Pylance Incorrect Unreachable Code Error

Expected behavior

This error shouldn't appear for code after the if statement.

Actual behavior

Despite the default values for arguments, it still says any code beyond the if statement is unreachable.

Logs

XXX
rchiodo commented 3 months ago

Thanks for your issue. This is by design. You're not fully typing your function. From the typechecker's perspective, argument arg1 can never be none because you assigned it type str.

This code would fix the problem:

def test(arg1: str | None = None, arg2 = False):
    if arg2:
        print('Made it this far')
        return
    elif arg1 is not None:
        print('Made it to here')
        return

    print('Made it all the way')

test()

or this:

def test(arg1 = None, arg2 = False):
    if arg2:
        print('Made it this far')
        return
    elif arg1 is not None:
        print('Made it to here')
        return

    print('Made it all the way')

test()

If you switch to typeCheckingMode=basic, Pylance will actually show an error on your original function definition:

image

chilipepperpizza commented 3 months ago

Ah that makes sense, did not know it was looking for nullability to be explicitly specified. Thanks for the heads up on the typecheckingmode setting.