_StrainableAttribute type does not allow None as argument

Bug #2110401 reported by Yuto Takano
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Beautiful Soup
New
Undecided
Unassigned

Bug Description

This bug is about one of the type hints provided with BeautifulSoup4.

When filtering an attribute with a lambda function, BeautifulSoup will provide an input argument of None to the lambda if the attribute does not exist on elements. However, the current type hint for `_StrainableAttribute` does not allow None as the lambda's argument, resulting in type checkers complaining if the case is handled.

Python Version: 3.11.4
BeautifulSoup Version: 4.13.4 with "html.parser"
System: Windows 11

Reproduction:

    import bs4
    html = '<html><body><a>bar</a></body></html>'
    soup = bs4.BeautifulSoup(html, 'html.parser')
    links = soup.find_all('a', href=lambda x: ".org" in x)
    # This type checks (lambda is Callable[[str], bool]), but will throw at runtime

    import bs4
    html = '<html><body><a>bar</a></body></html>'
    soup = bs4.BeautifulSoup(html, 'html.parser')
    links = soup.find_all('a', href=lambda x: x is not None and ".org" in x)
    # This will work at runtime, but will fail type checks (lambda is Callable[[str|None], bool])

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.