Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TYPE_CHECKING in ternary expression #15856

Open
igoose1 opened this issue Aug 11, 2023 · 0 comments
Open

TYPE_CHECKING in ternary expression #15856

igoose1 opened this issue Aug 11, 2023 · 0 comments

Comments

@igoose1
Copy link

igoose1 commented Aug 11, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants