Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Consider makingTemplate andInterpolation generic at runtime #133970

Open
Assignees
sobolevn
Labels
3.14bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-typingtriagedThe issue has been accepted as valid by a triager.type-featureA feature request or enhancement
@sobolevn

Description

@sobolevn

Feature or enhancement

Template andInterpolation will once be supported by type-checkers. And it might be worth adding generics support for these types.

Example

fromstring.templatelibimportTemplate,Interpolationfromurllib.parseimportquote_plusdomain='example.com'query='python string formatting is too complex'template=t'https://{domain}?q={query}'defquote_url(interp:Interpolation[str])->str:returnquote_plus(interp.value)defformat_url(template:Template)->str:parts= []forpartintemplate:matchpart:casestr()ass:# regular stringparts.append(s)caseInterpolation(str(),expression='query')asinterp:parts.append(quote_url(interp))caseInterpolation(value):parts.append(value)return''.join(parts)print(format_url(template))

Here we can see thatInterpolation[str] can be useful in users' code.

We can also benefit from genericTemplate, where we can make it generic based on exactTypeVarTuple. Demo:

fromtypingimportAny,TypeVarTuple,Generic,UnpackTs=TypeVarTuple('Ts',default=Unpack[tuple[Any, ...]])classTemplate(Generic[*Ts]):def__new__(cls,*args:*Ts)->Template[*Ts]: ...# type: ignore[empty-body]classInterpolation: ...reveal_type(Template('a','b',Interpolation(),'d'))# Revealed type is "__main__.Template[Literal['a']?, Literal['b']?, __main__.Interpolation, Literal['d']?]"

https://mypy-play.net/?mypy=latest&python=3.13&gist=0dc13b3b926e1efb9783ab9b70d39ceb

This can potentially help type checkers to infer correctTemplate type.

Current state

Currenttypeshed definitions:https://github.com/python/typeshed/blob/main/stdlib/string/templatelib.pyi

Here's howTemplate is defined:

@finalclassTemplate:# TODO: consider making `Template` generic on `TypeVarTuple`strings:tuple[str, ...]interpolations:tuple[Interpolation, ...]def__new__(cls,*args:str|Interpolation)->Template: ...def__iter__(self)->Iterator[str|Interpolation]: ...def__add__(self,other:Template|str)->Template: ...@propertydefvalues(self)->tuple[Any, ...]: ...# Tuple of interpolation values, which can have any type

Ideally, it should be generic onTypeVarTuple

Here's howInterpolation is defined:

@finalclassInterpolation:value:Any# TODO: consider making `Interpolation` generic in runtimeexpression:strconversion:Literal["a","r","s"]|Noneformat_spec:str__match_args__= ("value","expression","conversion","format_spec")def__new__(cls,value:Any,expression:str,conversion:Literal["a","r","s"]|None=None,format_spec:str=""    )->Interpolation: ...

Ideally, it should be generic onvalue.Interpolation[str] means thatvalue isstr andInterpolation[tuple[int, int]] means thatInterpolation has avalue for typetuple[int, int]

Proposal

From runtime's part with only need to addPy_GenericAlias, that's it.

Is it too late for feature freeze? This is a minor detail, so I hope it is not :)

I have a PR ready.

CC@srittau@JelleZijlstra@lysnikolaou

Linked PRs

Metadata

Metadata

Assignees

Labels

3.14bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-typingtriagedThe issue has been accepted as valid by a triager.type-featureA feature request or enhancement

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions


    [8]ページ先頭

    ©2009-2025 Movatter.jp