-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Unconstrained type variable combined with isinstance() doesn't seem to work #1539
Comments
I'm guessing that s might be of a non-str, non-bytes type, and mypy doesn't recognize "else: raise" as a type guard. I'm currently in day-job avoidance, so I'd better not go find out by replacing the "raise" with "return s". |
The reason the example doesn't work is that after the To make the example work, mypy could perhaps somehow keep track of the fact that |
Oh dang. I totally missed that the errors were about the return type, not about the + operators. Oh well. Since I blogged about this and linked to this issue from the blog, you can expect some more drive-by comments. |
Actually this particular program really is invalid because If you change both return statements to |
@rwbarton True, I got it wrong. In any case, this is a pretty subtle issue and doesn't look like a high-priority one. |
Hi ... I realize this is necromancy, but I'm running into this trying to type some existing code:
The intent is that this function will translate anything it's capable of translating -- a string -- and return everything else untouched. Mypy doesn't like this very much: export.py:60: error: Incompatible return value type (got "str", expected "T") ... But, of course, T is a str in this case -- but mypy doesn't seem to be able to dynamically constrain typevars. |
Or |
That's a good point -- but in this case, I think using Since I arrived here via google, I think a workaround for this lack of type constraining is likely to use something like @overload; I have since used something like the following: T = TypeVar('T')
@overload
def localize(v: str) -> str: ...
@overload
def localize(v: T) -> T: ...
def localize(v: T) -> Union[str, T]:
if isinstance(v, str):
return loctable.detokenize(v, default='')
return v |
Not sure this is a bug or not...
This gets errors on both
return
lines:Why? The isinstance() checks look like they should provide sufficient guards.
The text was updated successfully, but these errors were encountered: