Why doesn't fractions.Fraction support positional sub-patterns?

86 views Asked by At
lst = [1, 2, 3]
match lst:
  case list((1, 2, 3)):
    print(2)

gives 2 as output, but,

from fractions import Fraction

frctn = Fraction(1, 2)

match frctn:
  case Fraction(1, 2):
    print(1)

gives,

TypeError: Fraction() accepts 0 positional sub-patterns (2 given)

any specific reasoning for allowing positional sub-patterns for some types while not allowing them for some types?

1

There are 1 answers

0
Code-Apprentice On

Positional subpatterns in a class are declared using the __match_args__ magic attribute. See here for details. It appears that Fraction doesn't declare this attribute, so you must use named subpatterns instead:

Fraction(numerator=1, denominator=2)

See Point() accepts 0 positional sub-patterns (2 given)