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 errorNotImplemented 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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With