-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Strict Optional
checking
#1450
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
Comments
Wouldn't the typing on member initialization also rely on similar control flow analysis? (e.g. in "Attribute that Gets Initialized to None," etc.) |
Can you open new issues for the follow-up tasks? At least:
|
if I have an |
Thanks! There was some implicit stuff going on that tripped me up. |
(copied from internal discussion)
Proposal
With one exception, make MyPy enforce optional semantics as specified in PEP 484:
The one exception will be in the case of instance variables defined in the class body. These variables may be assigned
None
while having a non-Optional
type, provided that they are initialized to a non-None
value by the end of__init__
. They may be initialized in__init__
itself, or in any method onself
that__init__
calls, or in__new__
. Mypy will not check these variables for use before assignment to a non-None
value in__init__
or called methods, though it may make sense to add that at some point in the future.The purpose of this exception is to allow variables to be typed in a common place rather than scattered around
__init__
.Here’s how this would look in particular:
Make
None
a real typeIt supports a limited set of operations.
Optional[x]
is the same asUnion[x, None]
, and this is generally different from justx
.Infer
Optional[...]
fromNone
default valueIf
[not] value
checkIf
value is [not] None
checkassert x
Similar for
assert [not] x
or/and
Generators/comprehensions with condition check
Overloading with
None
The new overload syntax (I can’t remember whether it’s in PEP 484 already) would allow overloading based on
None
values:Class Variable that Gets Initialized to
None
Attribute that Gets Initialized to
None
Future/Out of Scope Work for Initial Version
Functions without Explicit Return with Non-Optional Return Type
We’ll need to do some control flow analysis to handle cases like this, so we shouldn't implement this initially.
Development Plan
Will probably need to start with #1278 as a first step (but not something to be merged separately). Will be behind a feature flag initially and turned on by default later.
The text was updated successfully, but these errors were encountered: