Improve template typing with specialized version
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Accessibilité débutants
- 35/100
Piste de recherche
Aucun fichier cible, test ou point d’entrée n’est nommé. Commencez par examiner les signatures proposées de Template, specialized Template, Interpolation et convert, puis cherchez un accord sur la conception et le nombre d’interpolations prises en charge avant de définir ce que devrait inclure la couverture de typage complète.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
This is the basic idea I had to improve typing for templates:
from collections.abc import Iterator
from types import GenericAlias
from typing import Any, Generic, Literal, TypeVar, final, overload, TypeAlias
_T = TypeVar("_T")
_T1_co = TypeVar("_T1_co", covariant=True)
_T2_co = TypeVar("_T2_co", covariant=True)
class __BaseTypingTemplate:
@overload
def __new__(cls, *args: str) -> __Special0.Template: ...
@overload
def __new__(cls, arg1: str, arg2: Interpolation[_T1_co], /, *args: str) -> __Special1.Template[_T1_co]: ...
@overload
def __new__(cls, arg1: str, arg2: Interpolation[_T1_co], arg3: str, arg4: Interpolation[_T2_co], /, *args: str) -> __Special2.Template[_T1_co, _T2_co]: ...
@overload
def __new__(cls, *args: str | Interpolation[Any]) -> Template: ...
def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...
@final
class Template(__BaseTypingTemplate):
strings: tuple[str, ...]
interpolations: tuple[Interpolation[Any], ...]
def __iter__(self) -> Iterator[str | Interpolation[Any]]: ...
def __add__(self, other: Template | __Special0.Template | __Special1.Template, /) -> Template: ...
@property
def values(self) -> tuple[Any, ...]: ...
__GeneralTemplate = Template # Alias we need in the specialized classes to make referencing it possible
class __Special0:
@final
class Template(__BaseTypingTemplate):
strings: tuple[str]
interpolations: tuple[()]
def __iter__(self) -> Iterator[str]: ...
@overload
def __add__(self, other: __GeneralTemplate, /) -> __GeneralTemplate: ...
@overload
def __add__(self, other: __Special0.Template, /) -> __Special0.Template: ...
@overload
def __add__(self, other: __Special1.Template[_T1_co], /) -> __Special1.Template[_T1_co]: ...
@overload
def __add__(self, other: __Special2.Template[_T1_co, _T2_co], /) -> __Special2.Template[_T1_co, _T2_co]: ...
@property
def values(self) -> tuple[()]: ...
class __Special1:
@final
class Template(__BaseTypingTemplate, Generic[_T1_co]):
strings: tuple[str, str]
interpolations: tuple[Interpolation[_T1_co]]
def __iter__(self) -> Iterator[str | Interpolation[_T1_co]]: ...
@overload
def __add__(self, other: __GeneralTemplate, /) -> __GeneralTemplate: ...
@overload
def __add__(self, other: __Special0.Template, /) -> __Special1.Template[_T1_co]: ...
@overload
def __add__(self, other: __Special1.Template[_T2_co], /) -> __Special2.Template[_T1_co, _T2_co]: ...
@overload
def __add__(self, other: __Special2.Template[_T1_co, _T2_co], /) -> __GeneralTemplate: ... # 3 but we stop at 2 for now
@property
def values(self) -> tuple[_T1_co]: ...
class __Special2:
@final
class Template(__BaseTypingTemplate, Generic[_T1_co, _T2_co]):
strings: tuple[str, str, str]
interpolations: tuple[Interpolation[_T1_co], Interpolation[_T2_co]]
def __iter__(self) -> Iterator[str | Interpolation[_T1_co] | Interpolation[_T2_co]]: ...
def __add__(self, other: Template, /) -> Template: ...
@property
def values(self) -> tuple[_T1_co, _T2_co]: ...
@final
class Interpolation(Generic[_T1_co]):
value: _T1_co
expression: str
conversion: Literal["a", "r", "s"] | None
format_spec: str
__match_args__ = ("value", "expression", "conversion", "format_spec")
def __new__(
cls, value: _T1_co, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = ""
) -> Interpolation[_T1_co]: ...
def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...
@overload
def convert(obj: _T, /, conversion: None) -> _T: ...
@overload
def convert(obj: object, /, conversion: Literal["r", "s", "a"]) -> str: ...
Side note: Before, the interpolation's value was invariant instead of covariant. I'm not sure why exactly, since interpolations and templates only have readonly attributes. For now I made them covariant.
My idea is basically making specialized version of Template. Since "class overloading" is not really a thing, this was the idea I came up with. We have the __SpecialX namespaces to be able to create multiple Template classes. Everything that should not be exposed I made "private", aka double underscored. Alternatively we could del of course.
What you might also notice is that the __new__ method always switches between str and Interpolation, exactly like __iter__ returns elements. This design choice has multiple reasons:
- This matches the
__iter__output and how (I think) templates are stored internally and therefore it would make it very easy for type checkers to support literal templates (t"...") with these specialized versions. Any literal could just be interpreted as a__new__call and it would make their typing much better as well. - This is the minimal way fully represent any template (up to n specialized templates we would support). If we removed some
strargs in the middle, then we would have to do so for every combination. This would already explode the amount of overloads. If we would add morestrargs, this would be even worse. - The final
argsofstrallows for morestrelements at the end for free. Havingargsin the middle or multiple times is not possible or logically sound.
This example only shows up to 2 interpolations. I would type it up to at least 8 interpolations.
Also, the base class is there for convenience and maybe could be factored out.
In summary I think this would be the perfect addition, especially to make it easy for type checkers to have more support the literal template syntax better.
What are your thoughts? Generally a good idea or some worries? Anything that could be simplified?
- Langage dominant
- Python
- Étoiles
- 5.1k
- Forks
- 2.1k
- Merge moyen
- 2 j 5 h
- PR mergées (30 j)
- 122
Préparer son environnement
- Aucun Dockerfile ni fichier Docker Compose
- Aucun modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de python/typeshed
-
`networkx.set_edge_attributes` should support scalar value + namePeut-être pris @Fire162 l’a pris il y a 10 jours. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 67/100
Les mainteneurs répondent en général sous 1 jour
-
false alarm on decode callPeut-être pris @jw9829 l’a pris il y a 38 jours. Ouvertehelp wanted stubs: false positive
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
python/typeshed#16441 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
Don't run pyright basic checks on projects with strict pyright settings in CIPeut-être pris @Mohith1612 l’a pris il y a 74 jours. Ouverteproject: infrastructure
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
python/typeshed#16005 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
stubs: improvement
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
python/typeshed#15548 · 5 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
stubs: improvement
Difficulté 2/5 1-3 heures Accessibilité débutants 64/100
python/typeshed#15529 · 5 commentaires ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de python/typeshed
Issues similaires
-
bug ready-for-dev
Difficulté 1/5 1-3 heures Accessibilité débutants 92/100
OpenHands/extensions#897 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
tensorflow/datasets#11253 ·
Les mainteneurs répondent en général sous 1 jour
-
fix(core): a config section with all keys commented out crashes startupPeut-être pris @Aryanbhargava18 l’a pris aujourd’hui. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 75/100
kubeflow/mcp-server#512 ·
Les mainteneurs répondent en général sous 1 jour
-
Stop trusting the compromised eMudhra CA certificatesPeut-être pris @anth-volk l’a pris aujourd’hui. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 82/100
PolicyEngine/uk-triple-lock#54 ·
Les mainteneurs répondent en général sous 1 jour
-
DBFS append mode silently overwrites existing filesPeut-être pris @IlyaKhalafi l’a pris aujourd’hui. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 77/100
fsspec/filesystem_spec#2429 ·
Les mainteneurs répondent en général sous 1 jour