-
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
Pylance incorrectly marks default parameters as a type issue #2879
Comments
You still need to add None as a type. python 3.10 def foo(a: str | None = None):
... else from typing import Optional
def foo(a: Optional[str] = None):
... |
I want to clarify that the above is not sufficient. By typing it explicitly as t = foo(a=None) However I want to explicitly disallow this such that the user can ONLY pass in value of type |
If the function is written to accept a |
@lee-hyunkyu, is your goal to be able to tell whether the caller (explicitly) provided a value for that parameter? |
@erictraut This is a flow that is supported by
As @debonte mentioned, one reason might be to determine whether the caller explicitly provided a value or not. Another is that it's a bit of a code smell for a user to use the function above by passing in # v1
def foo(a: str = None):
if a is None:
return "foo"
else:
return f"foo {a}"
# v2
def foo(a: Optional[str] = 1):
# a should be of type `str | int | None`
if type(a, int):
return "foo"
else if a is None:
return "foo None"
else:
return f"foo {a}"
## usage
# v1
foo(a=None) # "foo"
foo() # "foo"
# v2
foo(a=None) # "foo None"
foo() # "foo" The default behavior has remained the same (we return |
@debonte In case my previous comment didn't answer your question, no my goal isn't to tell whether a value was explicitly provided. I can't think of a scenario where that would matter but someone else might have a use for that functionality |
@lee-hyunkyu, mypy implicitly interprets a parameter with a def foo(a: str = None):
...
foo(a=None) This implicit interpretation of Here's the relevant section of PEP 484:
If you want the old behavior, pyright has an option to enable it. Look for |
@erictraut Hmm, I seemed to have completely misunderstood Given that and the PEPs, I'll close. Thanks for the clarification. |
@lee-hyunkyu, if you want to enforce that callers never pass @overload
def foo() -> str: ...
@overload
def foo(a: str) -> str: ...
def foo(a: str | None = None):
if a is None:
return "foo"
else:
return f"foo {a}" |
@erictraut That's incredibly helpful! I hadn't thought to use overloads to achieve the behavior I want. |
Environment data
Code Snippet
Expected behavior
I expect this to not throw an type check error and
a
to be typed asOptional[str]
withinfoo
.Actual behavior
a
is typed asstr
and this raises areportGeneralTypeIssues
errorLogs
The text was updated successfully, but these errors were encountered: