Title: Consider making `Template` and `Interpolation` generic at runtime · Issue #133970 · python/cpython · GitHub
Open Graph Title: Consider making `Template` and `Interpolation` generic at runtime · Issue #133970 · python/cpython
X Title: Consider making `Template` and `Interpolation` generic at runtime · Issue #133970 · python/cpython
Description: Feature or enhancement Template and Interpolation will once be supported by type-checkers. And it might be worth adding generics support for these types. Example from string.templatelib import Template, Interpolation from urllib.parse im...
Open Graph Description: Feature or enhancement Template and Interpolation will once be supported by type-checkers. And it might be worth adding generics support for these types. Example from string.templatelib import Temp...
X Description: Feature or enhancement Template and Interpolation will once be supported by type-checkers. And it might be worth adding generics support for these types. Example from string.templatelib import Temp...
Opengraph URL: https://github.com/python/cpython/issues/133970
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Consider making `Template` and `Interpolation` generic at runtime","articleBody":"# Feature or enhancement\n\n`Template` and `Interpolation` will once be supported by type-checkers. And it might be worth adding generics support for these types. \n\n## Example\n\n```python\nfrom string.templatelib import Template, Interpolation\nfrom urllib.parse import quote_plus\n\ndomain = 'example.com'\nquery = 'python string formatting is too complex'\ntemplate = t'https://{domain}?q={query}'\n\ndef quote_url(interp: Interpolation[str]) -> str:\n return quote_plus(interp.value)\n\ndef format_url(template: Template) -> str:\n parts = []\n for part in template:\n match part:\n case str() as s: # regular string\n parts.append(s)\n case Interpolation(str(), expression='query') as interp:\n parts.append(quote_url(interp))\n case Interpolation(value):\n parts.append(value)\n return ''.join(parts)\n\nprint(format_url(template))\n```\n\nHere we can see that `Interpolation[str]` can be useful in users' code.\n\nWe can also benefit from generic `Template`, where we can make it generic based on exact `TypeVarTuple`. Demo:\n\n```python\nfrom typing import Any, TypeVarTuple, Generic, Unpack\n\nTs = TypeVarTuple('Ts', default=Unpack[tuple[Any, ...]])\n\nclass Template(Generic[*Ts]):\n def __new__(cls, *args: *Ts) -> Template[*Ts]: ... # type: ignore[empty-body]\n \nclass Interpolation: ...\n \nreveal_type(Template('a', 'b', Interpolation(), 'd'))\n# Revealed type is \"__main__.Template[Literal['a']?, Literal['b']?, __main__.Interpolation, Literal['d']?]\"\n```\n\nhttps://mypy-play.net/?mypy=latest&python=3.13&gist=0dc13b3b926e1efb9783ab9b70d39ceb\n\nThis can potentially help type checkers to infer correct `Template` type.\n\n## Current state\n\nCurrent `typeshed` definitions: https://github.com/python/typeshed/blob/main/stdlib/string/templatelib.pyi\n\nHere's how `Template` is defined:\n\n```python\n@final\nclass Template: # TODO: consider making `Template` generic on `TypeVarTuple`\n strings: tuple[str, ...]\n interpolations: tuple[Interpolation, ...]\n\n def __new__(cls, *args: str | Interpolation) -> Template: ...\n def __iter__(self) -> Iterator[str | Interpolation]: ...\n def __add__(self, other: Template | str) -> Template: ...\n @property\n def values(self) -> tuple[Any, ...]: ... # Tuple of interpolation values, which can have any type\n```\nIdeally, it should be generic on `TypeVarTuple`\n\nHere's how `Interpolation` is defined:\n\n```python\n@final\nclass Interpolation:\n value: Any # TODO: consider making `Interpolation` generic in runtime\n expression: str\n conversion: Literal[\"a\", \"r\", \"s\"] | None\n format_spec: str\n\n __match_args__ = (\"value\", \"expression\", \"conversion\", \"format_spec\")\n\n def __new__(\n cls, value: Any, expression: str, conversion: Literal[\"a\", \"r\", \"s\"] | None = None, format_spec: str = \"\"\n ) -> Interpolation: ...\n```\n\nIdeally, it should be generic on `value`. `Interpolation[str]` means that `value` is `str` and `Interpolation[tuple[int, int]]` means that `Interpolation` has a `value` for type `tuple[int, int]`\n\n## Proposal\n\nFrom runtime's part with only need to add `Py_GenericAlias`, that's it.\n\nIs it too late for feature freeze? This is a minor detail, so I hope it is not :)\n\nI have a PR ready.\n\nCC @srittau @JelleZijlstra @lysnikolaou \n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-133976\n* gh-134029\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/sobolevn","@type":"Person","name":"sobolevn"},"datePublished":"2025-05-13T13:15:18Z","url":"https://github.com/python/cpython/issues/133970"}
| 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:b5e45b29-feb2-f48b-9e30-d2a772dd7cb4 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9060:B1603:368EF7F:488EB0D:6B0049FB |
| html-safe-nonce | 1f98cf53e197000192d84c4b51350cffb49f8f9a098cd9114565f0aa2cd39d83 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MDYwOkIxNjAzOjM2OEVGN0Y6NDg4RUIwRDo2QjAwNDlGQiIsInZpc2l0b3JfaWQiOiIxODg0NzU2MDcyMTg3NTc4ODc1IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 290a0f0cb7802fc8cd27876db9749581a39e47411f3a472d4552df656057d9da |
| hovercard-subject-tag | issue:3060050306 |
| 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/cpython/133970/issue_layout |
| twitter:image | https://opengraph.githubassets.com/7724a63e476fa36eda59d017eda67c6c32dc30ae58cf5b535c0b1749fffa4b80/python/cpython/issues/133970 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/7724a63e476fa36eda59d017eda67c6c32dc30ae58cf5b535c0b1749fffa4b80/python/cpython/issues/133970 |
| og:image:alt | Feature or enhancement Template and Interpolation will once be supported by type-checkers. And it might be worth adding generics support for these types. Example from string.templatelib import Temp... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | sobolevn |
| hostname | github.com |
| expected-hostname | github.com |
| None | f9517bf360d46638a1e5e7daee7158842fe5ef43c9000afa0e127564a7c2f39b |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| 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 | b27c5dde30676028abd5c5fc53ce5c9b625f8281 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width