MyPy error: Expected type in class pattern; found "Any"

MyPy error: Expected type in class pattern; found "Any"

想要将 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():
            ...