-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
default value for overloaded optional parameters #7333
Comments
You should only set the default on one of the overloads (the one that will get taken if the argument is not given). Otherwise mypy does not know which overload to use if the defaulted argument is not given. |
But then you can get an error like:
Code I'm trying it on:
|
I just stumbled upon this as well. It seems to me that you can solve this by adding a * before the parameter that is actually optional in one of the overloads. So, something like:
You will need to alternately re-order the arguments for that to work, since the required literal must be the only thing after * for each overload. Hope this helps! |
@JelleZijlstra can this issue be re-opened? Clearly the solution in #7333 (comment) doesn't work according to #7333 (comment), and #7333 (comment) seems like a work-around which probably doesn't work properly with non-keyword arguments in function calls given the |
@stianjensen's workaround should work in all cases, although it may need a lot of tricky overloads. |
Hmm... can you give a working example? Testing what is described in #7333 (comment) results in:
for me... |
Well @rggjan, my take away from @stianjenson (which I don't think I ever would have though of on my own ... thanks!) is that keyword only arguments is simply the cost of the ticket out of strife with overloads and default values. Personally, I'm happy to make all arguments involved in the overload variations keyword-only, as default-values no longer have any ordering requirement. And yes, function calls will need argument keywords ... but I think avoiding that is the kind of developer laziness/easiness that really doesn't have much or any value given the cost involved. |
Python 3.7.4, typing_extensions 3.7.4, mypy 0.720
I'm trying to use
Literal
and@overload
to change the result type of a function depending on a boolean switch.This issue is not specific to Literal, but it makes it easier to produce an easy to understand real-life use case.
Everything works great as long as the parameter is mandatory:
mypy output:
25: error: Item "None" of "Optional[int]" has no attribute "to_bytes"
However, if I set a default value:
mypy output:
Workaround
Add
# type: ignore
on line 11. The error on line 25 is still reported.Expected behaviour
In each of the signatures of an
@overload
'ed function, the allowed default values of an optional parameter should be the Union of type annotations from all the signatures.The text was updated successfully, but these errors were encountered: