redis-py
redis-py copied to clipboard
Best way to receive the return value when the type hint is Union[Awaitable[int], int]?
I noticed the return value type hint of redis-py functions are always like: Union[Awaitable[int], int]: (e.g. redis.commands.core.py:L4824)
def hlen(self, name: str) -> Union[Awaitable[int], int]:
"""
Return the number of elements in hash ``name``
For more information see https://redis.io/commands/hlen
"""
return self.execute_command("HLEN", name)
When I receive the value as normal
dict_size = redis.hlen("dict_key")
assert dict_size < 10
Pylance will remind me
Operator "<=" not supported for types "Awaitable[int] | int" and "Literal[10]"
Operator "<=" not supported for types "Awaitable[int]" and "Literal[10]"
How to let Pylance know I am not calling the function in asynchronous way, so I can mitigate this type checking error?
That smells like a typing bug in the library. Awaitable
s should really only be returned when using the async client...
I'm also facing this issue. I there any update?
def llen(self, name: str) -> Union[Awaitable[int], int]:
"""
Return the length of the list ``name``
For more information see https://redis.io/commands/llen
"""
Many of the methods with Union[Awaitable[int], int]
require a type guard check, or what is the best way to get around it? :thinking:
Similarly for almost ALL functions in commands/core.py, they're annotated to return ResponseT
(or similar) which is Union[Awaitable, Any]
which is picked up by PyCharm as just Awaitable
. So passing e.g. r.get(key)
's result to anything that expects bytes/str results in a warning
This issue is marked stale. It will be closed in 30 days if it is not updated.
Still relevant, I presume
I'm hitting this, but in the reverse; mypy complains when using the asyncio version that it might return int, even when I'm importing from redis.asyncio and calling await
against the function. Any update?
I'm also facing the same issue.
Seems like this should be mentioned here. One of the linked issues above contains a reply with a solution/workaround: https://github.com/redis/redis-py/issues/3091#issuecomment-1903419256
The suggested solution is to install the type stub package: https://pypi.org/project/types-redis/
Worked for me :+1:
Afaiu, this is the old way of getting typing hints for redis but the package now has its own typing hints that are incomplete. Because of that pylance won't tell you to go install available type stubs but it will complain because the included types return types are wrong.