Typing stubs for pyserial

3.5.0.20260408 · active · verified Sat Apr 11

types-pyserial provides static type annotations for the popular pyserial library. It is part of the typeshed project, which centrally maintains type stubs for the Python standard library and many third-party packages. These stubs are used by static type checkers like MyPy or Pyright to verify code correctness without running it, enhancing development and catching potential issues early. The package is regularly updated, often daily, to reflect changes and improvements in the corresponding runtime library, pyserial. This version aims to provide accurate annotations for pyserial==3.5.*.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic serial communication using `pyserial`. With `types-pyserial` installed, a type checker will provide accurate type hints and catch errors for functions, classes, and methods imported from the `serial` module, such as `Serial`, `write`, `readline`, and `is_open`. The `SERIAL_PORT` environment variable is used for demonstration, but you should replace it with your device's actual serial port.

import os
from serial import Serial

# Replace with your actual serial port name (e.g., 'COM1' on Windows, '/dev/ttyUSB0' on Linux)
SERIAL_PORT = os.environ.get('SERIAL_PORT', '/dev/ttyUSB0')
BAUDRATE = 9600

def communicate_with_serial(port: str, baud: int) -> None:
    ser: Serial | None = None
    try:
        # The `Serial` class is correctly typed by types-pyserial
        ser = Serial(port, baud)
        print(f"Opened serial port {port} at {baud} baud.")

        # Example: Write data
        message_to_send = b"Hello, device!\n"
        ser.write(message_to_send)
        print(f"Sent: {message_to_send.decode().strip()}")

        # Example: Read data (with a timeout)
        ser.timeout = 1 # seconds
        received_data = ser.readline()
        if received_data:
            print(f"Received: {received_data.decode().strip()}")
        else:
            print("No data received within timeout.")

    except Exception as e:
        print(f"Error during serial communication: {e}")
    finally:
        if ser and ser.is_open:
            ser.close()
            print(f"Closed serial port {port}.")

if __name__ == "__main__":
    communicate_with_serial(SERIAL_PORT, BAUDRATE)

view raw JSON →