Replies: 3 comments 3 replies
-
This was specifically discussed when creating PEP 647, and it was rejected. Applying the TypeGuard to a If you want to narrow the type of So no, I think this would be a bad idea to extend PEP 647 in this manner, and I would strongly oppose any proposal to do so. |
Beta Was this translation helpful? Give feedback.
-
Can't argue with the extra complexity argument. But, I assume things would become a lot simpler with a separate type, say The use cases I see are purely with generic type narrowing using a method of self. What do you think, Eric? |
Beta Was this translation helpful? Give feedback.
-
I found an alternative that works in my case using mypy 1.3.0, but not with Pyright (Pylance v2023.5.30 with Pyright 1.1.307) from typing import Literal, final
from abc import ABC, abstractmethod
class Result(ABC):
@property
@abstractmethod
def is_ok(self) -> bool: ...
@final
class Ok(Result):
is_ok: Literal[True] = True
def __init__(self, value: str) -> None:
self.value = value
@final
class Err(Result):
is_ok: Literal[False] = False
def __init__(self, err: str) -> None:
self.err = err
def fetch_data() -> Ok | Err:
return Ok("ok")
res = fetch_data()
if res.is_ok:
reveal_type(res) # type is Ok |
Beta Was this translation helpful? Give feedback.
-
@erictraut since this is your PEP I wonder what you'd think about expanding the scope of the
TypeGuard
to support narrowing theSelf
type when it is generic.Let me give you an example with a monad type that I'm using:
Say I have this function that resolves to
Result
during the runtime:When I want to narrow down the type, I can do this:
TypeGuard
spec, I can't do it like this:Since
TypeGuard
method requires an argument that will be "type guarded".But conceptually I want to "type guard" self type when it is generic.
Beta Was this translation helpful? Give feedback.
All reactions