[这个答案是假设的]
FWIW,这就是我完成匹配/案例的方式 - 对我来说似乎比从头开始获取新变量并且没有聪明的可能性使用变量来比较或实际常量更直观:
替代匹配/案例提案
SOME_CONSTANT = 0
some_string = "qwert"
def example_matchcase (var):
match var
# simple literal case
case 10:
print("case 1")
# basic check including another variable
case len(some_string):
print("case 2")
# check against a constant
case SOME_CONSTANT:
print("case 3")
# if-like statement
case ? 0 < var < 10:
print("case 4")
case ? callable(var):
print("case 5")
case ? hasattr(var, 'isnumeric') and var.isnumeric():
print("case 6")
# slide statement
case ? var < 50:
print("case 7a")
slide
case ? var < 25:
print("case 7b")
slide
case ? var < 10:
print("case 7c")
slide
case ? var in (1,3,5,7):
print("case 8 - early prime:", var)
# 'else' instead of 'case _:'
# more meaningful, _ looks like an unused variable and potentially conflicts with gettext
else:
print("unknown value")
""" real-world example where this would be very elegant """
INTERF_MUPDF = 0
INTERF_PDFIUM = 1
INTERF_POPPLER = 2
def render_thumbnails (interface):
match interface
case INTERF_MUPDF:
from interfaces import InterfMupdf
_interface = InterfMupdf()
case INTERF_PDFIUM:
from interfaces import InterfPdfium
_interface = InterfPdfium()
case INTERF_POPPLER:
from interfaces import InterfPoppler
_interface = InterfPoppler()
case ? callable(interface):
print("using a custom interface")
_interface = interface
else:
raise Exception("`interface` must be a constant or a callable object")