Title: Strict `Optional` checking · Issue #1450 · python/mypy · GitHub
Open Graph Title: Strict `Optional` checking · Issue #1450 · python/mypy
X Title: Strict `Optional` checking · Issue #1450 · python/mypy
Description: (copied from internal discussion) Proposal With one exception, make MyPy enforce optional semantics as specified in PEP 484: By default, None is an invalid value for any type, unless a default value of None has been provided in the funct...
Open Graph Description: (copied from internal discussion) Proposal With one exception, make MyPy enforce optional semantics as specified in PEP 484: By default, None is an invalid value for any type, unless a default valu...
X Description: (copied from internal discussion) Proposal With one exception, make MyPy enforce optional semantics as specified in PEP 484: By default, None is an invalid value for any type, unless a default valu...
Opengraph URL: https://github.com/python/mypy/issues/1450
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Strict `Optional` checking","articleBody":"(copied from internal discussion)\n## Proposal\n\nWith one exception, make MyPy enforce optional semantics as specified in PEP 484:\n\n> By default, None is an invalid value for any type, unless a default value of None has been provided in the function definition.\n> …\n> As a shorthand for Union[T1, None] you can write Optional[T1].\n\nThe 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 on `self` 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.\nThe purpose of this exception is to allow variables to be typed in a common place rather than scattered around `__init__`.\n\nHere’s how this would look in particular:\n### Make `None` a real type\n\nIt supports a limited set of operations. `Optional[x]` is the same as `Union[x, None]`, and this is generally different from just `x`.\n\n``` python\n def f(x: Optional[str]) -> None:\n x.startswith('x') # error, None has no startswith\n\n def g(x: str) -> None: ...\n\n g(None) # error\n```\n### Infer `Optional[...]` from `None` default value\n\n``` python\n def f(x: str = None) -> None:\n # type of x is Optional[str]\n ...\n\n f('') # ok\n f(None) # ok\n```\n### If `[not] value` check\n\n``` python\n def f(x: str = None) -> None:\n if x:\n # type of x should be str here\n x.startswith('x') # should be fine\n else:\n # type of x should be Optional[str] here\n x.startswith('x') # error\n```\n### If `value is [not] None` check\n\n``` python\n def f(x: str = None) -> None:\n if x is not None:\n # type of x should be str here\n x.startswith('x') # should be fine\n else:\n # type of x should be None here\n x.startswith('x') # error\n```\n### `assert x`\n\n``` python\n def f(x: str = None) -> None:\n assert x\n x.startswith('x') # should be fine\n```\n\nSimilar for `assert [not] x`\n### or/and\n\n``` python\n def f(x: str = None, y: str = None) -> None:\n x and x.startswith('x') # should be fine (and easy)\n x is None or x.startswith('x') # should be fine\n x and y and x.startswith('x') and y.startswith('x') # fine\n\n def g(x: str = None) -> str:\n return x or \"default\"\n```\n### Generators/comprehensions with condition check\n\n``` python\n a = ... # type: List[Optional[int]]\n b = [x for x in b if x]\n # type of b should be List[int]\n```\n### Overloading with `None`\n\nThe new overload syntax (I can’t remember whether it’s in PEP 484 already) would allow overloading based on `None` values:\n\n``` python\n @overload\n def f(x: None) -> None: ...\n @overload\n def f(x: str) -> int: ...\n\n def f(x):\n if x:\n return int(x)\n else:\n return None\n\n f('') # type is str\n f(None) # type is None\n```\n### Class Variable that Gets Initialized to `None`\n\n``` python\n class A:\n x = None # type: str\n def __init__(self) -> None:\n x = \"value\"\n\n class B:\n x = None # type: str\n def __init__(self) -> None:\n self.setup()\n\n def setup(self) -> None:\n x = \"value\"\n```\n### Attribute that Gets Initialized to `None`\n\n``` python\n class A:\n x = None # type: str\n def __init__(self) -> None:\n self.x = None # type: ignore\n\n def load(self, f: IO[str]) -> None:\n self.x = f.read()\n\n def process(self) -> None:\n print(x + 'x') # should be fine?\n\n class B:\n def __init__(self) -> None:\n self.x = None # type: Optional[str]\n\n def load(self, f: IO[str]) -> None:\n self.x = f.read()\n\n def process(self) -> None:\n assert self.x # needed, otherwise next line is an error\n print(x + 'x') # fine\n```\n## Future/Out of Scope Work for Initial Version\n### Functions without Explicit Return with Non-Optional Return Type\n\nWe’ll need to do some control flow analysis to handle cases like this, so we shouldn't implement this initially.\n\n``` python\n def f(x: int) -> int:\n if x > 0:\n return 5\n else:\n pass # uh oh, no return value here\n```\n## Development Plan\n\nWill 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.\n","author":{"url":"https://github.com/ddfisher","@type":"Person","name":"ddfisher"},"datePublished":"2016-04-28T20:22:25Z","url":"https://github.com/python/mypy/issues/1450"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:4c00dd56-a53a-0b9b-9313-df9a6e6502f8 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BB16:160FAB:38F63C:4FE34C:6B005E4B |
| html-safe-nonce | 131d004159bc3a2d368c3b3ccd5a071a317629b284d09e5608ea14383d43b983 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQjE2OjE2MEZBQjozOEY2M0M6NEZFMzRDOjZCMDA1RTRCIiwidmlzaXRvcl9pZCI6IjI3NDU1Nzc0NjA4Nzg4MjcwODMiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 5ea8ae372d76441cf3b0680043509d7e7922dfd664752c83df91a0a4235d4850 |
| hovercard-subject-tag | issue:151734450 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/mypy/1450/issue_layout |
| twitter:image | https://opengraph.githubassets.com/44886e49377a244d64b4ff924dd562880a8513ecf8c77e7aa7f1fc9d8731ca9a/python/mypy/issues/1450 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/44886e49377a244d64b4ff924dd562880a8513ecf8c77e7aa7f1fc9d8731ca9a/python/mypy/issues/1450 |
| og:image:alt | (copied from internal discussion) Proposal With one exception, make MyPy enforce optional semantics as specified in PEP 484: By default, None is an invalid value for any type, unless a default valu... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ddfisher |
| hostname | github.com |
| expected-hostname | github.com |
| None | 29be975efff6507a5d135de9c7d634cf7ff8f0c55222a64386ab3202209aaf73 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/mypy git https://github.com/python/mypy.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 7053637 |
| octolytics-dimension-repository_nwo | python/mypy |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 7053637 |
| octolytics-dimension-repository_network_root_nwo | python/mypy |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | eacd927ba6112e3b01ba99c762bd699a4a4f5df7 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width