Typing Stubs for Channels

4.3.0.20260408 · active · verified Thu Apr 16

types-channels is a stub package providing type hints for the `channels` library, which enables asynchronous communication for Django. It allows static type checkers like MyPy to understand the types used within `channels` code, improving code quality and maintainability. It is part of the `typeshed` project and is currently at version 4.3.0.20260408, with releases frequently updated to track upstream `channels` and `typeshed` changes.

Common errors

Warnings

Install

Imports

Quickstart

To use `types-channels`, install it alongside the `channels` library and a type checker like MyPy (`pip install channels types-channels mypy`). Then, simply write your `channels` code with type annotations. MyPy will automatically pick up the stubs from `types-channels` when checking your code. For instance, save the example consumer above as `my_consumer.py` and run `mypy my_consumer.py` in your terminal. If correctly configured, MyPy should report no errors, validating your type hints based on the installed stubs.

import asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
from typing import Dict, Any, Union

# Example consumer, save as `my_consumer.py`
class MyConsumer(AsyncWebsocketConsumer):
    async def connect(self) -> None:
        await self.accept()
        print("WebSocket connected!")

    async def disconnect(self, close_code: int) -> None:
        print(f"WebSocket disconnected with code: {close_code}")

    async def receive(self, text_data: Union[str, None] = None, bytes_data: Union[bytes, None] = None) -> None:
        if text_data:
            response: Dict[str, Any] = {"message": f"Received: {text_data}"}
            await self.send(text_data=str(response))
        print("Received data.")

async def main():
    # This part is just to make the example runnable for demonstration of type hints.
    # In a real application, connect and disconnect would be called by the ASGI server.
    consumer = MyConsumer()
    await consumer.connect()
    # Simulate a received message for type checking
    await consumer.receive(text_data="Hello from client!")
    await consumer.disconnect(1000)

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →