Typing stubs for qrcode
types-qrcode is a type stub package providing external type annotations for the 'qrcode' Python library. It enables static type checkers like Mypy and Pyright to analyze code that uses 'qrcode', ensuring type correctness without altering runtime behavior. This package is part of the Typeshed project, which releases updates frequently (sometimes daily) to maintain alignment with the 'qrcode' library's versions.
Warnings
- gotcha The `types-qrcode` package provides only type hints; it does not contain any runtime code. The actual `qrcode` library must be installed separately (e.g., `pip install qrcode`) for your application to function.
- breaking Type stubs are versioned to match the runtime library. If the `qrcode` library undergoes a major version update (e.g., from 8.x to 9.x), the `types-qrcode` stubs for the older version might become incompatible, leading to type-checking errors even if your runtime code still works.
- gotcha For 'qrcode' to generate and save images (e.g., PNG, JPEG), the Pillow library is required. This is typically installed with `pip install qrcode[pil]`.
- gotcha Effective QR code usage involves design considerations (contrast, size, content). Type checkers won't flag poor design choices like low contrast (dark QR on dark background), inverted colors (light QR on dark background), or excessively small QR codes, which can severely impact scannability and user experience. Always test generated QR codes with multiple scanners.
Install
-
pip install types-qrcode -
pip install qrcode[pil]
Imports
- qrcode
import qrcode
- QRCode
from qrcode import QRCode
- constants
from qrcode import constants
Quickstart
import qrcode
# Data to be encoded in the QR code
data = "https://www.example.com/your-data-here"
# Create QR code instance with desired parameters
# version: controls the size of the QR Code (1 to 40). None for auto-sizing.
# error_correction: controls the error correction level.
# box_size: size of each box (pixel) in the QR Code.
# border: thickness of the border (minimum 4).
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H, # High error correction
box_size=10,
border=4,
)
# Add data to the QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code instance
# Pillow (PIL) is required for saving as an image file like PNG
img = qr.make_image(fill_color="black", back_color="white")
# Save the image
# In a real application, you might use os.path.join for paths
output_filename = "my_qrcode.png"
img.save(output_filename)
print(f"QR Code saved to {output_filename}")