TYPE_CHECKING in ternary expression
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing both Python examples with mypy and compare how TYPE_CHECKING is handled in the ternary expression versus the if/else form. Trace the ternary-expression type-checking entry point to determine whether the behavior is a bug or should be documented. Done means the example is correctly validated or the differing behavior is clearly documented, with regression coverage if the behavior changes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100