Adafruit CircuitPython Typing

1.12.3 · active · verified Fri Apr 17

adafruit-circuitpython-typing provides Python type hints, specifically Protocol definitions and TypeAliases, for common hardware interface types found in CircuitPython, such as BlockDevice, SPIDevice, and AnyDisplay. It facilitates static type checking for CircuitPython applications developed in CPython environments. The library is currently at version 1.12.3 and is actively maintained with frequent minor releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use the `BlockDevice` and `AnyDisplay` types in function signatures. These types are primarily used for static type checking to ensure compatibility with various hardware interfaces, not for runtime instantiation. The example includes mock implementations to illustrate how objects conforming to the protocols would be used.

from adafruit_circuitpython_typing import BlockDevice, AnyDisplay
from typing import Protocol

# Define a mock BlockDevice for demonstration purposes
class MockBlockDevice(Protocol):
    def readblocks(self, start_block: int, buf: bytearray) -> None:
        print(f"Reading block {start_block}")

    def writeblocks(self, start_block: int, buf: bytearray) -> None:
        print(f"Writing block {start_block}")

    def ioctl(self, operation: int, arg: int) -> int:
        print(f"IOCTL operation {operation} with arg {arg}")
        return 0

# A function that expects any BlockDevice
def format_device(device: BlockDevice) -> None:
    print(f"Formatting a device of type: {type(device).__name__}")
    device.writeblocks(0, bytearray(512))

# A function that expects any display type
def initialize_display(display: AnyDisplay) -> None:
    print(f"Initializing display of type: {type(display).__name__}")
    # In a real scenario, this would call display methods like show(), fill(), etc.


# Example usage:
my_sd_card = MockBlockDevice()
format_device(my_sd_card)

# A mock display object (in reality, it would be from a CircuitPython display driver)
class MockDisplay:
    def show(self) -> None: pass
    def fill(self, color: int) -> None: pass

my_oled_display = MockDisplay()
initialize_display(my_oled_display)

print("Type hints used successfully for static analysis.")

view raw JSON →