Type Stubs for Chardet
types-chardet is a PEP 561 type stub package that provides static type information for the `chardet` library. It allows type checkers like Mypy, Pyright, or PyCharm to perform static analysis and detect type-related errors in code that uses `chardet` for character encoding detection, without affecting the runtime behavior of the application. This package is maintained as part of the broader Typeshed project. The current version is 5.0.4.6, and it follows the release cadence of the Typeshed project, which releases updates for third-party stubs regularly.
Warnings
- breaking The `chardet` library, starting from version 5.1.0, includes its own inline type annotations. If you are using `chardet>=5.1.0`, you should uninstall `types-chardet` to avoid potential conflicts with the package's native type information.
- gotcha `types-chardet` provides only type stubs; it does not install the actual `chardet` runtime library. For your code to run, `chardet` must be installed separately (e.g., `pip install chardet`).
- gotcha The versioning of `types-chardet` follows Typeshed's policy, where the first three parts align with the `chardet` version it stubs (e.g., `5.0.4` for `chardet` 5.0.x), followed by a Typeshed-specific identifier. Direct version pinning between `chardet` and `types-chardet` can be complex and might sometimes lead to conflicts or missed type improvements.
- gotcha `chardet` underwent a significant rewrite in version 7.x, introducing substantial performance improvements, new features (like MIME type detection), and dropping support for older Python versions (now requiring Python 3.10+). While the public API remained largely compatible, be aware of the underlying changes and Python version requirements if migrating to `chardet` 7.x.
Install
-
pip install types-chardet
Imports
- detect
from chardet import detect
- UniversalDetector
from chardet import UniversalDetector
Quickstart
import chardet
def analyze_encoding(data: bytes) -> dict:
"""Detects the encoding of a byte string."""
result = chardet.detect(data)
print(f"Detected encoding: {result['encoding']} with confidence {result['confidence']}")
return result
# Example usage with bytes data
sample_data = "München ist die Hauptstadt Bayerns.".encode("windows-1252")
analysis = analyze_encoding(sample_data)
# Without types-chardet, a type checker might not flag if you passed
# a 'str' instead of 'bytes' to chardet.detect. With it, it would.
# try_wrong_data = analyze_encoding("This is a string") # Mypy/Pyright would flag this as an error