{"id":8737,"library":"types-channels","title":"Typing Stubs for Channels","description":"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.","status":"active","version":"4.3.0.20260408","language":"en","source_language":"en","source_url":"https://github.com/python/typeshed","tags":["typing","stubs","channels","async","asgi","mypy"],"install":[{"cmd":"pip install types-channels","lang":"bash","label":"Install types-channels"},{"cmd":"pip install 'channels<5'","lang":"bash","label":"Install compatible channels (example)"}],"dependencies":[{"reason":"Provides the actual runtime implementation that these stubs type-hint. You must install `channels` to use these type stubs effectively.","package":"channels","optional":false}],"imports":[{"note":"types-channels provides type hints for symbols imported from the `channels` library itself. You do not import directly from `types_channels` as it contains only stub files (.pyi) for static analysis, not runtime code.","symbol":"ProtocolTypeRouter","correct":"from channels.routing import ProtocolTypeRouter"}],"quickstart":{"code":"import asyncio\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nfrom typing import Dict, Any, Union\n\n# Example consumer, save as `my_consumer.py`\nclass MyConsumer(AsyncWebsocketConsumer):\n    async def connect(self) -> None:\n        await self.accept()\n        print(\"WebSocket connected!\")\n\n    async def disconnect(self, close_code: int) -> None:\n        print(f\"WebSocket disconnected with code: {close_code}\")\n\n    async def receive(self, text_data: Union[str, None] = None, bytes_data: Union[bytes, None] = None) -> None:\n        if text_data:\n            response: Dict[str, Any] = {\"message\": f\"Received: {text_data}\"}\n            await self.send(text_data=str(response))\n        print(\"Received data.\")\n\nasync def main():\n    # This part is just to make the example runnable for demonstration of type hints.\n    # In a real application, connect and disconnect would be called by the ASGI server.\n    consumer = MyConsumer()\n    await consumer.connect()\n    # Simulate a received message for type checking\n    await consumer.receive(text_data=\"Hello from client!\")\n    await consumer.disconnect(1000)\n\nif __name__ == '__main__':\n    asyncio.run(main())\n","lang":"python","description":"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."},"warnings":[{"fix":"Always import symbols from the actual `channels` library (e.g., `from channels.routing import ProtocolTypeRouter`), not `types_channels`.","message":"`types-channels` provides only type stub files (`.pyi`) for static analysis by tools like MyPy. It does not contain any executable Python code for runtime and should never be imported directly.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `types-channels` and `channels` are reasonably compatible. Check `typeshed` changelogs or `channels` release notes for guidance on compatibility if you encounter type errors. Consider pinning versions (e.g., `channels<5` for current stubs).","message":"Stub package versions (like `types-channels`) are typically designed for specific versions of their corresponding runtime library (`channels`). Using significantly mismatched versions can lead to incorrect type checking results or MyPy errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Verify MyPy's `follow_imports` setting. The default `normal` is usually sufficient. If MyPy reports 'Library 'channels' has no type information available', ensure `types-channels` is installed in the environment MyPy is checking.","message":"For MyPy to effectively use `types-channels`, ensure your MyPy configuration allows it to follow imports. Default settings usually work, but issues might arise with custom `mypy.ini` configurations.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Import symbols from the actual `channels` library instead (e.g., `from channels.layers import get_channel_layer`).","cause":"Attempting to import from the stub package `types_channels` directly, which only contains stub files and no runtime modules.","error":"ModuleNotFoundError: No module named 'types_channels'"},{"fix":"Install the `types-channels` package in the environment MyPy is using (`pip install types-channels`). Also, ensure MyPy is configured to check that environment.","cause":"MyPy cannot find type stubs for the `channels` library.","error":"error: Library \"channels\" has no type information available"},{"fix":"Review the specific type error message carefully. It might indicate an actual bug in your code, or a version incompatibility where the API signature in `channels` has changed, and the stubs are outdated (or vice versa). Update `channels` or `types-channels` to compatible versions, or adjust your code.","cause":"A type error reported by MyPy, often due to mismatched expectations between your code and the stubs, or incompatible versions of `channels` and `types-channels`.","error":"error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")"}]}