Skip to content

docs.python.org | 4.6. match Statements #106780

Closed

Description

Documentation

https://docs.python.org/3/tutorial/controlflow.html

I fixed the code as follows since points is not defined, still it does not work:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

points = [Point(0,7), Point(0,9)]

match points:
    case []:
        print("No points")
    case [Point(0, 0)]:
        print("The origin")
    case [Point(x, y)]:
        print(f"Single point {x}, {y}")
    case [Point(0, y1), Point(0, y2)]:
        print(f"Two on the Y axis at {y1}, {y2}")
    case _:
        print("Something else")

error:

Traceback (most recent call last):
  File "c:\Users\moham\OneDrive\Education\UDST\gpaCal.py", line 15, in <module>
    case [Point(0, y1), Point(0, y2)]:
          ^^^^^^^^^^^^
TypeError: Point() accepts 0 positional sub-patterns (2 given)

Linked PRs

Activity

  1. ghost added
    docs
    on Jul 15, 2023
  2. terryjreedy commented on Jul 15, 2023

    @terryjreedy
    Member

    That Point definition is in a previous example. The paragraph that follows explains the solution for matching positional parameters. In this case, add __match_args__ = ('x', 'y') to Point and the example works. I will augment the Point list example with a proper Point definition. Working on PR.

  3. added a commit that references this issue on Jul 15, 2023
  4. added a commit that references this issue on Jul 17, 2023
  5. added 2 commits that reference this issue on Jul 17, 2023
  6. added 2 commits that reference this issue on Jul 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docs

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions