gpt4 book ai didi

python - MyPy 错误 : Expected type in class pattern; found "Any"

转载 作者:行者123 更新时间:2023-12-05 05:44:34 26 4
gpt4 key购买 nike

想要将 MyPy 检查器添加到我的 html 抓取工具中。我设法修复了所有错误,除了这个 Expected type in class pattern

源代码:

from bs4 import BeautifulSoup

from bs4.element import Tag, NavigableString

soup = BeautifulSoup("""
<!DOCTYPE html>
<html>
<body>
EXTRA TEXT
<p>
first <b>paragraph</b>
<br>
<br>
second paragraph
</p>
</body>
</html>
""", "lxml")

tag = soup.select_one('body')

for el in tag.children:
match el:
case NavigableString():
...
case Tag(name="p"):
...
case Tag():
...

mypy example.py

错误:

example.py:24: error: Expected type in class pattern; found "Any"
example.py:26: error: Expected type in class pattern; found "Any"
example.py:28: error: Expected type in class pattern; found "Any"
Found 3 errors in 1 file (checked 1 source file)

那么,这个错误是什么意思呢?我该如何解决?

最佳答案

您可以使用 TYPE_CHECKING 加载具有类型的类

from typing import TYPE_CHECKING

if TYPE_CHECKING:

class NavigableString:
...

class Tag:
children: list[NavigableString | Tag]
name: str

class BeautifulSoup:
def __init__(self, markup: str, features: str | None) -> None:
...

def select_one(self, text: str) -> Tag:
...

else:
from bs4 import BeautifulSoup
from bs4.element import Tag, NavigableString

soup = BeautifulSoup(
"""
<!DOCTYPE html>
<html>
<body>
EXTRA TEXT
<p>
first <b>paragraph</b>
<br>
<br>
second paragraph
</p>
</body>
</html>
""",
"lxml",
)

tag = soup.select_one("body")

for el in tag.children:
match el:
case NavigableString():
...
case Tag(name="p"):
...
case Tag():
...

关于python - MyPy 错误 : Expected type in class pattern; found "Any",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71576361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com