Open
Description
This issue should be marked with "topic-ternary-expression" label.
Mypy doesn't understand TYPE_CHECKING
checked in a ternary expression.
Example 1
from typing import TYPE_CHECKING
from redis.asyncio import ConnectionPool
from redis.asyncio import Redis as OGRedis
from . import settings
Redis = OGRedis[bytes] if TYPE_CHECKING else OGRedis # Redis is Generic in stubs
async def func() -> None:
connection_pool = ConnectionPool.from_url(settings.redis_url)
async with Redis(connection_pool=connection_pool) as redis:
await redis.set(
name="test",
value="Hello World",
)
$ mypy project/
project/code.py:13: error: "object" has no attribute "__aenter__" [attr-defined]
project/code.py:13: error: "object" has no attribute "__aexit__" [attr-defined]
Found 2 errors in 1 file (checked 3 source files)
Example 2
from typing import TYPE_CHECKING
from redis.asyncio import ConnectionPool
from redis.asyncio import Redis as OGRedis
from . import settings
if TYPE_CHECKING: # these
Redis = OGRedis[bytes] # 4 lines
else: # are
Redis = OGRedis # the only difference
async def func() -> None:
connection_pool = ConnectionPool.from_url(settings.redis_url)
async with Redis(connection_pool=connection_pool) as redis:
await redis.set(
name="test",
value="Hello World",
)
$ mypy project/
Success: no issues found in 3 source files
That's either a bug or an expected behavior that can be documented. I can imagine a programmer spending an hour debugging and searching why his/her code isn't validated properly.