{"library":"types-redis","title":"Typing Stubs for Redis","description":"types-redis is a PEP 561 type stub package from the Python 'typeshed' project, providing static type annotations for the popular 'redis-py' library. It enables type-checking tools like MyPy, Pyright, and PyCharm to analyze code that uses the `redis` package, enhancing code quality and developer experience. This version, 4.6.0.20241004, aims to provide accurate annotations for redis==4.6.0. Typeshed stub packages are automatically released to PyPI frequently, often up to once a day.","status":"active","version":"4.6.0.20241004","language":"en","source_language":"en","source_url":"https://github.com/python/typeshed/tree/main/stubs/redis","tags":["type-hinting","redis","stubs","typeshed","mypy","pyright"],"install":[{"cmd":"pip install types-redis","lang":"bash","label":"Install `types-redis`"},{"cmd":"pip install redis 'redis[hiredis]' types-redis","lang":"bash","label":"Install with `redis-py` and optional `hiredis`"}],"dependencies":[{"reason":"Provides type hints for the 'redis-py' client library.","package":"redis","optional":false}],"imports":[{"note":"The core synchronous Redis client class. `types-redis` augments this class with type information for static analysis.","symbol":"Redis","correct":"from redis import Redis"},{"note":"The asynchronous Redis client class (aliased for clarity). `types-redis` provides stubs for `redis.asyncio` operations.","symbol":"AsyncRedis","correct":"from redis.asyncio import Redis as AsyncRedis"}],"quickstart":{"code":"import redis\nfrom typing import Optional, Any\nimport os\n\ndef get_redis_client() -> redis.Redis[Any]:\n    # In a real application, you'd get connection details from environment variables or a configuration system.\n    # Using os.environ.get for quickstart, assuming Redis is running locally on default port.\n    host = os.environ.get('REDIS_HOST', 'localhost')\n    port = int(os.environ.get('REDIS_PORT', 6379))\n    db = int(os.environ.get('REDIS_DB', 0))\n    \n    print(f\"Connecting to Redis at {host}:{port}/{db}\")\n    # types-redis provides the type hints for the Redis client.\n    return redis.Redis(host=host, port=port, db=db, decode_responses=True)\n\ndef set_and_get_value(client: redis.Redis[Any], key: str, value: str) -> Optional[str]:\n    client.set(key, value)\n    result: Optional[str] = client.get(key)\n    print(f\"Set '{key}':'{value}', Retrieved: '{result}'\")\n    return result\n\ndef increment_counter(client: redis.Redis[Any], key: str) -> int:\n    initial_value = client.setnx(key, 0) # Set if not exists, returns 1 if set, 0 otherwise\n    current_count: int = client.incr(key)\n    print(f\"Incremented '{key}' to {current_count}\")\n    return current_count\n\nif __name__ == \"__main__\":\n    # Ensure a Redis server is running, e.g., via docker: docker run -p 6379:6379 -it redis:latest\n    try:\n        r_client = get_redis_client()\n        r_client.ping() # Test connection\n        print(\"Successfully connected to Redis!\")\n\n        user_id_key: str = \"user:profile:101\"\n        user_data: str = \"{'name': 'Jane Doe', 'email': 'jane.doe@example.com'}\"\n        set_and_get_value(r_client, user_id_key, user_data)\n\n        page_views_key: str = \"app:metrics:page_views\"\n        increment_counter(r_client, page_views_key)\n        increment_counter(r_client, page_views_key)\n\n        # Example of using a typed command return value\n        all_keys: list[str] = r_client.keys('user:*')\n        print(f\"Found user keys: {all_keys}\")\n\n    except redis.exceptions.ConnectionError as e:\n        print(f\"Could not connect to Redis: {e}. Please ensure Redis server is running.\")\n    except Exception as e:\n        print(f\"An unexpected error occurred: {e}\")\n    finally:\n        # Clean up example keys (optional)\n        if 'r_client' in locals() and r_client.ping(): # Check if connected before deleting\n            r_client.delete(user_id_key, page_views_key)\n            print(\"Cleaned up example keys.\")","lang":"python","description":"This quickstart demonstrates how to initialize a synchronous Redis client and perform basic operations like setting/getting values and incrementing a counter. The type hints are automatically provided by `types-redis` for the `redis` library. Note that `decode_responses=True` is often used for string handling, making the type hints more directly applicable to Python strings."},"warnings":[{"fix":"If using `redis-py>=5.0.0`, uninstall `types-redis` via `pip uninstall types-redis`. The `redis` package itself will provide the necessary type hints.","message":"The `redis` package (redis-py) now includes its own type annotations/stubs starting from version 5.0.0. If you are using `redis>=5.0.0`, you should uninstall `types-redis` to avoid conflicts and redundant stubs. Continued use may lead to type-checking issues.","severity":"breaking","affected_versions":"redis-py >= 5.0.0"},{"fix":"Ensure that the major and minor version of `types-redis` (e.g., `4.6.0` from `4.6.0.20241004`) matches the version of your `redis-py` installation. Consider pinning versions in your `requirements.txt`.","message":"`types-redis` versions are linked to `redis-py` versions. For example, `types-redis==4.6.0.YYYYMMDD` is designed for `redis-py==4.6.0`. Using mismatched major/minor versions (e.g., `types-redis` for `redis-py 4.x.x` with `redis-py 3.x.x` or `redis-py 5.x.x`) can lead to incorrect or missing type hints.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Be aware that not every aspect of the `redis` library might be fully typed. For critical untyped sections, consider adding local type ignores or contributing to typeshed.","message":"Type stubs provided by typeshed, including `types-redis`, might be 'partial,' meaning some less common features or specific edge cases might have `Any` annotations or lack full type coverage. If you find missing annotations, contributions to typeshed are encouraged.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Regularly update your type checker to its latest stable version. If encountering issues, consider temporarily pinning `types-redis` to an older version compatible with your type checker, or upgrade your Python interpreter if the features are specific to a newer Python version.","message":"Older versions of type checkers (e.g., MyPy, Pyright) might not fully support newer Python typing features used in `types-redis` stubs. This could lead to silent loss of type checking precision (e.g., `Any` types appearing unexpectedly) or outright errors.","severity":"gotcha","affected_versions":"Typeshed stubs using newer typing features with older type checkers"},{"fix":"Ensure you are using a relatively recent version of `redis-py` (ideally >=4.3.0 for better async typing) and the corresponding `types-redis` version. If issues persist, refer to typeshed's issue tracker for `redis` stubs.","message":"Early versions of `redis.asyncio` in `redis-py` had some type definition issues, which also affected `types-redis`. While many have been resolved, unexpected type errors might still occur with specific `redis-py` and `types-redis` combinations when using the async client.","severity":"gotcha","affected_versions":"Potentially older versions of `redis-py` (pre-5.0.0) with `types-redis`"}],"env_vars":null,"last_verified":"2026-04-05T00:00:00.000Z","next_check":"2026-07-04T00:00:00.000Z"}