Skip to content

Type Narrowing of Final variable is lost in function #1800

@bvolkmer

Description

@bvolkmer

Describe the Bug

Let's start with the minimal example:

param: Final[str | None] = ""
if param is None:
    raise ValueError()
reveal_type(param)


def foo() -> None:
    reveal_type(param)

The first type is correctly revealed as str but the second inside the function is revealed as str | None. While this would be correct (in my option), if param was not Final, since the variable could change between function definition and function execution, this should not be the case for a Final variable, which explicitly should not change. So given, the Final is respected (which pyrefly should assume), param will never be something else than a str.

(Off-Topic: in this very simple example, one could argue that param should be revealed as a str from the start, as it is initialized as a str and should never change. But that is another topic)

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AxVqigAaOpRgA3GCID6TYjAA66YqkqoaiQcKgBtOA0p0APnQByudDAC6dALx1lIF6ohg66zfQhxL1jCIqnShEqh%2BMHQAaiIArjAAopTUlAAUAJSqkjLyijBp3lpZ6KqqmDCeYLi4mXQAtAB8ATbB6GES0rJQCswFRTQlqtW1GSCiIHEM0HAk5IggAMR0AKrTUBBMdGBx6ADG09ZwZViV27w0qAxy6HE02DDp%2BDqsDBkNzUaUbR2SDHGUdpgFwWO4Pb50YD4AC%2BbnQ4xAZEkYCgpEIDFoUAoywACqRkai6GgsHh8HQ9tZIGwAVcINZCKplgBlGBRAAWDAYxDgiAA9LykZVUYReGxeTB0LzMLg9nBeRT0FSaYdJecTKgpBEoKhsLByZSINTNCq6LhiCrZqoyAw2dZ6jJKHA6e0nC4AMyEACMACY4SBoRNUAcIDIhLAKMScAQ5v6gA

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions