Replies: 2 comments 6 replies
-
Could you provide a single, self-contained, minimal code sample that demonstrates your issue? Your code above is piecemeal and refers to symbols that are not defined. I could try to guess at the definition of these symbols, but I'd appreciate it if you could provide a single, complete sample. |
Beta Was this translation helpful? Give feedback.
2 replies
-
TypeGuard not working as I expected too. Here's a basic TypeGuard example and it does not seem to work: # Pylance v2024.11.3
# Pyright v1.1.390
# Return True if the supplied value is None, empty, or contains only whitespace.
def is_blank(value: str | None) -> TypeGuard[None]:
return not value or value.isspace()
value: str | None = os.getenv("MY_VAR")
if (is_blank(value)):
value = "not None"
strVal: str = value # not expecting warning: "None" is not assignable to "str" (PylancereportAssignmentType) |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello,
I am taking our code base and adding type hints to it. In the course of doing this, I have created functions that are
TypeGuard
s to help with the type hints. As mentioned in the title, some of theTypeGuard
s do not seem to work as I would expect (which is not the same as not working as anybody else would expect: I am trying to convey my expectations might be completely wrong.Although the details are probably not relevant, some idea of the design might be relevant. I have a class
NameInterface
, from which a series of other classes inherit (GtvNm
,PtvNm
,UGtvNm
, etc., roughly a dozen subclasses):A function
name_from_str
analyses a string and returns an object of the appropriate type:Then, I have defined a bunch of type aliases and
TypeGuard
functions to help type hinting when working with the object. I have done it like so:Unfortunately, when used in code, the function as written above does not seems to not act as a type guard. For instance:
will "complain" (i.e. put squiggles under) the
.level
function/property call. I would have expected that the function acting as aTypeGuard
would then understand thatcomp
is aGenericTarget
and would see/consider that it is guaranteed to have a.level
member. I have tried putting both checks on different lines (thinking maybe it is because of theand
), but it makes no difference.Are my expectations wrong ? Are there restrictions on
TypeGuard
s I am not aware of (read the python documentation, quite a few forums, tried to find the info on my own). ? Is this a bug ? Probably a bug, but in my code or in the type checker ? Might it be that what I am doing is not actually type narrowing in some sense ?I have a screen shot of the squigglies in Sublime Text using LSP-Pyright (not that it will help much, but to show what I mean).
Any insight or help will be welcome. Sorry for being verbose.
Beta Was this translation helpful? Give feedback.
All reactions