为何Python match匹配类型报错‘剩余模式不可达’,但type('a')==str为真?
问题解答
一、为什么会抛出SyntaxError
在Python的match-case语法里,case list:这种写法属于名称捕获模式——它会把匹配到的任何值都绑定到变量list上,而不是用来匹配list这个类型对象。这就导致第一个case会匹配所有输入,后面的case str:永远没机会执行,Python能检测到这种不可达代码,所以抛出SyntaxError: name capture 'list' makes remaining patterns unreachable。
如果要正确匹配类型对象(比如你代码里type('a')返回的str类),得改成条件匹配的形式:
match type('a'): case cls if cls is list: print('a list') case cls if cls is str: print('a string')
要是你本来想匹配值的类型(而非类型对象本身),更合理的写法是直接匹配值:
match 'a': case list(): print('a list') case str(): print('a string')
二、为什么type('a')==str的结果为True
type('a')会返回字符串对应的类型对象,也就是str类本身。用==比较时,两边是同一个对象(str类的唯一实例),所以结果为True。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

