-
Notifications
You must be signed in to change notification settings - Fork 767
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
How do I describe a special return type for a subclass? #6512
Comments
Pyright (the type checker that pylance is built upon) is working correctly here. It's telling you that you've defined two overloads that "overlap". That means the same set of arguments can match both overloads, but the return types are incompatible. This makes it possible for a call to result in an incorrect type. Consider the following. def as_date(v: datetime) -> date:
return v
x = myfunc(as_date(datetime(1, 2, 3)))
reveal_type(x) # Statically evaluated as "str", but returns "int" at runtime If you're not concerned about this potential "unsoundness", you can suppress the error with a If this is your code and you're able to modify it, you may want to consider redesigning it to avoid this fragility. I don't know how this function is intended to be used, so I can't offer any more specific suggestions. If you're interested in learning more about overloads and what it means for them to be "overlapping", you might be interested in reading the draft chapter that I recently wrote and submitted for inclusion in the Python typing spec. |
Thanks, Eric. The key is that it returns different type based on if the parameter is date or datetime. As the datetime is a subclass of date, I struggle to describe the return typing. So I’d do “if param type is a special subclass (datetime) then return int, if the parameter type is anything else from the date class (eg date itself) then return string”. In python I can’t write a typing like “date except datetime” to make it non-overlapping, but I don’t know how to pass pylance (and mypy) |
The Python type system doesn't allow you to express If you're not able to change the design of this function, then you'll need to live with the unsoundness. You can suppress the error if you don't want to see it. |
Pylance gives me:
Overload 1 for "myfunc" overlaps overload 2 and returns an incompatible type Pylance[reportOverlappingOverload]
for the below snippet:The text was updated successfully, but these errors were encountered: