在PyCharm中如何解决这个类型提示错误“Unexpected type(s)”?
我在PyCharm(Python 3.14)中遇到了这种类型提示错误:
Unexpected type(s):
(str | None)
Possible type(s):
(LiteralString)
(str)
但看不出我的代码到底哪里有问题。
filename: str | None = None
...
if filename: # i.e. not None
filename = filename
with open("files\\" + filename, "wb") as f: # <- this line has the error on filename
pass
我到底哪里做错了?
解决方案
看起来PyCharm无法推断 if filename: 语句意味着 None 情况在其主体中不可能出现。尝试添加一个具有更严格类型的新变量。
if filename:
fn: str = filename
with open("files\\" + fn, "wb") as f:
pass
备选方案
以下这行代码干扰了静态类型检查器对类型的推断:
filename = filename
因为删除它之后不会再显示任何警告。
既然我们确定 filename 在 if 块内不会是 None,那么我们只需要确保静态类型检查器也知道这一点。我们可以使用 assert 来强制确保它。
更改后,你的代码就不会再因该警告而被标记,如下所示:
filename: str | None = None
if filename: # i.e. not None
filename = filename
assert filename is not None # added to enforce the fact that it's not None
with open("files\\" + filename, "wb") as f:
pass
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。