Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pattern match on Ellipsis or NotImplemented

How can I match ... (Ellipsis) and NotImplemented in Python's pattern? The naive attempt of

import random
x = random.choice([..., NotImplemented])

match x:
    case NotImplemented:
        print("1")
    case ...:
        print("2")

fails in two ways:

  • ... is a syntax error
  • NotImplemented is treated as an identifier not a constant, so matches everything!

Using Ellipsis instead of ... runs into the same problem as NotImplemented, in that it matches everything.

like image 701
Eric Avatar asked Nov 28 '25 12:11

Eric


1 Answers

Accessing these names via . notation on the builtins module means that match treats them as constants:

import builtins

match x:
    case builtins.NotImplemented:
        print("1")
    case builtins.Ellipsis:
        print("2")

Another approach is to use the Type() notation of pattern matching, and match on the types of these constants instead of the values:

NotImplementedType = type(NotImplemented)
EllipsisType = type(Ellipsis)

match x:
    case NotImplementedType():
        print("1")
    case EllipsisType():
        print("2")
like image 122
Eric Avatar answered Nov 30 '25 02:11

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!