Title: Overhaul the python typing system to make typing a 'first class citizen' with a dedicated typing syntax, like match patterns · Issue #953 · python/typing · GitHub
Open Graph Title: Overhaul the python typing system to make typing a 'first class citizen' with a dedicated typing syntax, like match patterns · Issue #953 · python/typing
X Title: Overhaul the python typing system to make typing a 'first class citizen' with a dedicated typing syntax, like match patterns · Issue #953 · python/typing
Description: Pythons implementation of typing at the language level has been very limited, with only the absolute minimal changes to the grammar being implemented: type annotations: a: int return type annotations: def () -> int: Both of these syntaxe...
Open Graph Description: Pythons implementation of typing at the language level has been very limited, with only the absolute minimal changes to the grammar being implemented: type annotations: a: int return type annotatio...
X Description: Pythons implementation of typing at the language level has been very limited, with only the absolute minimal changes to the grammar being implemented: type annotations: a: int return type annotatio...
Opengraph URL: https://github.com/python/typing/issues/953
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Overhaul the python typing system to make typing a 'first class citizen' with a dedicated typing syntax, like match patterns","articleBody":"Pythons implementation of typing at the language level has been very limited, with only the absolute minimal changes to the grammar being implemented:\r\n- type annotations: `a: int`\r\n- return type annotations: `def () -> int:`\r\n\r\nBoth of these syntaxes are just normal expressions that are evaluated (or are just strings if `__future__.annotations` is on).\r\n\r\nThat has meant that the entirety of the typing landscape has been implemented 'in the language' using existing syntax and functionality to try and emulate typing as a first class language feature.\r\n\r\nThis has lead to modifications to the standard library to attempt to better support these usages (eg: [special casing `type[...]`](https://github.com/gvanrossum/cpython/blob/4575c01b750cd26377e803247c38d65dad15e26a/Objects/abstract.c#L182), defining `__or__` on `type` and the introduction of `__class_getitem__` [among](https://www.innersloth.com/games/among-us/) others). So all these objects now have a dual nature, they have functions to support their 'normal' usages, and also a bunch of functions to support building type annotations.\r\n\r\nThe authors of PEP-586 [have commented](https://www.python.org/dev/peps/pep-0586/#adding-more-concise-syntax) on this problem(thanks @sobolevn):\r\n> we feel overhauling the syntax of types in Python is not within the scope of this PEP: it would be best to have that discussion in a separate PEP\r\n\r\nDue to the nature of typing being 'implemented in the language' instead of in the grammar/interpreter has lead to a myriad of complexities, edge cases, limitations and confusion. I will list a few of these side effect here. also showing a more optimal syntax that would be possible if typing were to be overhauled:\r\n\r\n### Fake types and type alias\r\nFake types such as `None` and `ForwardRef`s lead to runtime errors(either in annotations or upon calling `get_type_hints`):\r\n```py\r\nfrom typing import TypeAlias\r\n\r\nStr: TypeAlias = \"str\"\r\nInt: TypeAlias = \"int\"\r\n\r\na: Str | Int = 0 # SUS ALERT\r\n```\r\nThere could be a dedicated `typealias` keyword like other languages\r\n```py\r\ntypealias foo = int | str\r\n```\r\n(https://github.com/python/mypy/issues/11582)\r\n#### Shout out to NewType\r\n```py\r\nMyStr = NewType(\"MyStr\", str)\r\n```\r\nCould be\r\n```py\r\nnewtype MyStr = str\r\n```\r\n\r\n### Typing imports\r\nA large amount of types need to be imported from `typing`, leading to a boilerplate of imports in every module:\r\n```py\r\nfrom typing import NoReturn, TypedDict, TypeAlias, TypeVar, Generic, Protocol, etc, etc, etc, etc\r\n```\r\nThere could be a 'builtins' for type annotations that are usable by default.\r\n\r\nAlso there is no way to import a type statically, see #928\r\n\r\n### Type parameters\r\nAre one of the worst incantations imaginable:\r\n```py\r\nfrom typing import TypeVar, Generic\r\n\r\nT_cont = TypeVar(\"T_cont\", contravariant=True, bound=str)\r\n\r\nclass A(Generic[T_cont]):\r\n ...\r\n```\r\nCould be\r\n```py\r\nclass A[in T_cont: str]:\r\n ...\r\n```\r\n\r\nAlso you can't specify type parameters explicitly on function call sites:\r\n```py\r\nfoo_result: int | str = foo(1, \"a\")\r\nbar(foo_result)\r\n```\r\nCould be:\r\n```py\r\nbar(foo[int | str](1, \"a\"))\r\n```\r\n\r\n### Literal syntax\r\n```py\r\na: Literal[1, 2] = 1\r\n```\r\nCould be\r\n```py\r\na: 1 | 2 = 1\r\n```\r\n\r\n### cast\r\nYet another import, and very clunky to boot.\r\nAnd why is the type first? everywhere else(`isinstance`, `issubclass`, type annotations) types go second.\r\n```py\r\ncast(int, a)\r\n```\r\nCould be `as` or similar like other languages:\r\n```py\r\na as int\r\n```\r\n\r\n### Callable\r\nIn error messages mypy shows this as `(int, str) -> bool`\r\n```py\r\na: Callable[[int, str], bool]\r\n```\r\nCould be\r\n```py\r\na: (int, str) -> bool\r\n```\r\n\r\n### Confusion\r\nBecause all these type machineries exist at runtime, it creates very confusing situations where an annotation is used in a value position:\r\n```py\r\nA = int | str\r\nA() # is this valid?\r\nfoo(A) # is this valid?\r\nB: type[int | str] = int | str # is this valid?\r\n```\r\n\r\nhttps://github.com/microsoft/pyright/issues/2522 shows that it's very easy to overlook this situation.\r\n\r\n\r\n# Match Patterns\r\n[Enter `match/case` statements](https://www.python.org/dev/peps/pep-0622/), which have their own unique language level syntax for dealing with all the concepts needed in a comprehensive way. For example matching a union of strings: `\"a\" | \"b\"` which in a typing annotation would just be evaluated as a normal expression and raise a `TypeError`.\r\n```py\r\nmatch \"a\":\r\n case \"a\" | \"b\": # 😳😳😳😳😳😳😳😳😳😳😳😳😳😳😳😳\r\n print(\"AMONGUS\")\r\n```\r\n\r\nInstead of endlessly implementing special casing and workarounds, please overhaul the entire implementation of typing in the language from the ground up. Currently typing in python is very rough around the edges and could be vastly improved based upon the experience and usages gathered over the years since it's inception.\r\n\r\n# Proposal\r\nAdd the concept of a 'type context' that has it's own unique semantic meaning, separating the type realm functionality from the value(value context) realm functionality. This would make things such as the type union `|` much simpler and consistent (see issue where some types are not actually types at all, and don't have `__or__`). These operations would still produce type machinery representations:\r\n\r\n```py\r\nclass A:\r\n a: int | str\r\nA.__annotations__ # {'a': UnionType[int, str]}\r\n```\r\n\r\nAnd these machinereies could be constructed manually in a 'value context' when needed:\r\n```py\r\na = UnionType(int, str)\r\n```\r\n\r\n### Example\r\n```py\r\nBar = 1 | 2\r\n # ^ value context\r\ntypealias Foo = 1 | 2\r\n # ^ type context\r\n```\r\n\r\n### Evaluating type syntax\r\n```py\r\nfrom __future__ import annotations\r\nfrom typing import get_type_hints\r\n\r\nclass A:\r\n x: \"a\" | \"b\"\r\n\r\nget_type_hints(A) # Currently will raise a TypeError\r\n```\r\nUnder the hood, `get_type_hints` simply `eval`s the annotation as a module level expression, I suggest adding a `eval_type` function that will evaluate it as a `type context` expression, not a `value context`\r\n\r\n\r\n","author":{"url":"https://github.com/KotlinIsland","@type":"Person","name":"KotlinIsland"},"datePublished":"2021-11-20T06:45:40Z","url":"https://github.com/python/typing/issues/953"}
| 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:15d6b3e8-37cb-bea8-2dda-0de127475ba3 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B9A6:3F9D33:21EA0AE:2E0C72A:6B0024FE |
| html-safe-nonce | f68fde7551502e5eae901f1046e7da409cdce377e59b642d2da76f75b10caa65 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCOUE2OjNGOUQzMzoyMUVBMEFFOjJFMEM3MkE6NkIwMDI0RkUiLCJ2aXNpdG9yX2lkIjoiMjMyOTMxMDkzOTk0NzQ3NjIyMiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 93a391eddb97d447f14bb94d694b18029cc0e97f0d1a6b22170b29de7864cffc |
| hovercard-subject-tag | issue:1059077728 |
| 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/typing/953/issue_layout |
| twitter:image | https://opengraph.githubassets.com/cb1af7aedca402680ab9a6849a86bbf2d4f05bc6c71cb05d69ae2fbcb8ccf72f/python/typing/issues/953 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/cb1af7aedca402680ab9a6849a86bbf2d4f05bc6c71cb05d69ae2fbcb8ccf72f/python/typing/issues/953 |
| og:image:alt | Pythons implementation of typing at the language level has been very limited, with only the absolute minimal changes to the grammar being implemented: type annotations: a: int return type annotatio... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | KotlinIsland |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4eb4cba0d69f045374ac15de9666d22b0961e1d555cc3824f36b7734c00c78e0 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/typing git https://github.com/python/typing.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 24604008 |
| octolytics-dimension-repository_nwo | python/typing |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 24604008 |
| octolytics-dimension-repository_network_root_nwo | python/typing |
| 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 | 44c658b24abf00491fb7ae5f56d42c9f38cbeab2 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width