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

Support python3.10 structural pattern matching (PEP 634-636) #3920

Closed
3 tasks done
irgolic opened this issue Mar 20, 2022 · 0 comments · Fixed by #3921
Closed
3 tasks done

Support python3.10 structural pattern matching (PEP 634-636) #3920

irgolic opened this issue Mar 20, 2022 · 0 comments · Fixed by #3921
Labels
bug V1 Bug related to Pydantic V1.X

Comments

@irgolic
Copy link
Contributor

irgolic commented Mar 20, 2022

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Feature

Python 3.10 introduces the new match syntax. https://peps.python.org/pep-0636/

Example:

num = 5

match num:
    case 5:
        print('is five')
    case default:
        print('is not five')

They support matching on custom classes too, with the __match_args__ attribute.

class MyClass:
    __match_args__ = ('num1', 'num2')

    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2


myinstance = MyClass(5, 10)


match myinstance:
    case MyClass(5, num2):
        print(f'is 5 and {num2}')
    case MyClass(_, num2):
        print(f'is not 5 and is {num2}')

I've found myself adding this attribute to pydantic classes by hand, eventhough it seems pretty intuitive to me that the default behavior should match fields in the order that they were specified. So my code looks kind of like this:

class UpdateThing(BaseModel):
    __match_args__ = ("thing", "value")
    thing: Thing
    value: str


class AddThing(BaseModel):
    __match_args__ = ("index", "thing")
    index: int
    thing: Thing

Might as well add it natively?

I'm opening this issue to couple it with a PR :)

@irgolic irgolic added the bug V1 Bug related to Pydantic V1.X label Mar 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V1 Bug related to Pydantic V1.X
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant