Typing Stubs for Bleach
types-bleach provides static type checking stubs for the 'bleach' HTML sanitizing library. It enables type checkers like MyPy or Pyright to validate usage of `bleach` functions and classes without providing any runtime functionality itself. As part of typeshed, these packages are automatically released, potentially up to once a day, reflecting updates to the underlying library's API or improvements in type accuracy.
Warnings
- gotcha types-bleach is a stub-only package. It provides type annotations for the 'bleach' library and does not contain any executable code. You must install the 'bleach' library itself for runtime functionality.
- breaking Type stubs from typeshed (including types-bleach) can introduce changes that might cause your code to fail type-checking, even if the runtime library ('bleach') has not changed its API. This can occur with minor stub version bumps.
- gotcha The versioning scheme for typeshed stub packages like `types-bleach` is `X.Y.Z.YYYYMMDD`. The `X.Y.Z` part corresponds to the version of the runtime package ('bleach') that the stubs are targeted against and tested with. The `YYYYMMDD` suffix indicates the date the stub package was published on PyPI.
Install
-
pip install types-bleach -
pip install bleach types-bleach
Imports
- clean
from bleach import clean
- linkify
from bleach import linkify
Quickstart
import bleach
# Example usage of bleach with type hints
def process_html(user_input: str) -> str:
allowed_tags = ['a', 'p', 'b', 'i']
allowed_attrs = {'a': ['href', 'title']}
# The type checker will use types-bleach stubs to validate this call
cleaned_html: str = bleach.clean(
user_input,
tags=allowed_tags,
attributes=allowed_attrs,
strip=True
)
return cleaned_html
html_input = '<p>Hello, <script>alert("XSS!");</script><a href="http://example.com">world</a>!</p>'
output = process_html(html_input)
print(output)
# Expected output with type checking: <p>Hello, <a href="http://example.com">world</a>!</p>