-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
add stub for contextvars.pyi #1968
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
Conversation
@1st1 Can you have a quick look here? |
stdlib/3.7/contextvars.pyi
Outdated
_T = TypeVar('_T') | ||
|
||
class ContextVar(Generic[_T]): | ||
def __init__(self, name: str, *, default: _T) -> None: ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
default
is not a required parameter. It's not typing.Optional
either, as it is either of type _T
or not passed at all (None
is not a valid value).
A couple of examples:
# valid:
int_var: ContextVar[int] = ContextVar(default=1)
int_var: ContextVar[int] = ContextVar()
# invalid:
int_var: ContextVar[int] = ContextVar(default=None)
and
# valid:
int_var: ContextVar[Optional[int]] = ContextVar(default=1)
int_var: ContextVar[Optional[int]] = ContextVar(default=None)
int_var: ContextVar[Optional[int]] = ContextVar()
Here's a pure Python implementaion of PEP 567 / ContextVar
: https://github.com/MagicStack/contextvars/blob/master/contextvars/__init__.py#L111
I'm not sure how to express this in terms of typing
. Maybe
class ContextVar(Generic[_T]):
def __init__(self, name: str, *, default: _T=...) -> None: ...
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can write *, default: _T = ...
. Sorry for missing this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Jelle: If = ...
doesn't work, you can use an overload (once without, once with default
).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NP!
LGTM. I wish there was a way to express |
Yes, I couldn't think of a clean way. An approach I thought of was to define a fake type like
and with the proposed type annotations I don't think mypy would be able to infer that val is not MISSING in the else branch. So unless Guido can think of something better, we should probably go with Any. |
FWIW I think that the primary use-case for |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Go ahead and merge!
See PEP 567 and https://docs.python.org/dev/library/contextvars.html#module-contextvars.
Part of #1965.