简体   繁体   English

Python 带可选变量的模式匹配

[英]Python Pattern Matching with optional variables

I'm using mypy and I have two classes:我正在使用 mypy,我有两个类:

class Student:
    first_name: str
    ...

class City:
    id: int
    name: str
    ...

I have some db function that fetch the data and I end up with these two variables:我有一些 db function 可以获取数据,最后得到这两个变量:

student: Optional[Student] = ...
city: Optional[City] = ...

I want to do pattern match for each case of None or non-None data of both variables.我想对两个变量的 None 或非 None 数据的每种情况进行模式匹配。

I want to do different things for each case, this way:我想为每种情况做不同的事情,这样:

match student, city:
    case None, None:
        output = "they all none"
    case Student(), City():
        output = f"student: {student.first_name} lives in {city.name}"
    case _, _:
        output = "one of them is none..."

But mypy doesn't recognize student and city as non-None in the second case.但是在第二种情况下,mypy 不会将 student 和 city 识别为非 None。 I don't want to use # type: ignore我不想使用# type: ignore

EDITED to consider user19077881 suggestion.编辑以考虑 user19077881 的建议。 I would go with the classic ifs:我会 go 用经典的ifs:

if student==None and city==None:
    output = "they all none"
elif student==None or city==None:
    output = "one of them is none..."
else:
    output = f"student: {student.first_name} lives in {city.name}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM