Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match statement with object matching attribute type #4775

Closed
AiroPi opened this issue Mar 15, 2023 · 1 comment
Closed

Match statement with object matching attribute type #4775

AiroPi opened this issue Mar 15, 2023 · 1 comment
Labels
as designed Not a bug, working as intended

Comments

@AiroPi
Copy link

AiroPi commented Mar 15, 2023

Describe the bug
It seems that doing a "type checking" with the object UI in pattern matching seems to not work properly.

Code

class Test:
    def __init__(self, a: int | str):
        self.a: int | str = a

test = Test(5)

match test:
    case Test(a = int()):
        print(test.a + 3)
    case Test(a = str()):
        print(test.a + "3")

Expected behavior
By doing a match with Test(a = int()), python will check test is of type Test AND test.a is of type int.
But pyright "only assert" that test if of type Test. It keep the type int | str for test.a.

VS Code extension or command-line
Both, and in unofficial playground:
https://pyright-playground.decorator-factory.su/?gzip=H4sIAJKQEWQC_32NOwrDQAxEe51icLUiwY1xY8gt0i9is8YLjgmWyhw-EobgImQqoTefsooq7lVtIrgedUbObWuWc9K6zlfIhLYZ3lDb-XCFAvZnhhuEyLzKr2hMIxM9xcoC-w4U0XpQcZuHE59KX3t8wt0LLhj4R8an_mW6oeMP_NNLyNYAAAA%3D

@erictraut
Copy link
Collaborator

Yes, this is as designed. The type of the expression test is narrowed to type Test, but the type of test.a is not narrowed in this case. Narrowing is applied only to one expression, not both. Not surprisingly, mypy works the same way.

Your options are:

  1. Perform a cast.
  2. Create a nested match statement:
match test:
    case Test():
        match test.a:
            case int():
                print(test.a + 3)
            case str():
                print(test.a + "3")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
as designed Not a bug, working as intended
Projects
None yet
Development

No branches or pull requests

2 participants