Spec for subtypes of type variable constraints too vague
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 35/100
- Tipo de issue
- Documentação
- Clareza
- Precisa de esclarecimento
- Status de atividade
- Estagnada
- Stack de tecnologia
- python
- Domínio
- documentation
Direção de pesquisa
Comece por docs/spec/generics.rst, especialmente pela seção vinculada sobre variáveis de tipo com restrições, e revise os exemplos envolvendo C[bool], inferência de construtor e posições contravariantes. Leia as quatro regras propostas e a discussão existente nos comentários antes de determinar a semântica pretendida. A tarefa estará concluída quando houver um acordo e a especificação for atualizada para declarar claramente o comportamento.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
The spec is very vague when it comes to instantiating a type variable with constraints with a subtype of one of the constraints:
Let's look at a slightly more involved example:
class C[T: (int, str)]:
def __init__(self, t: T) -> None:
self.t: T = t
c = C(True)
The example in the spec implies that the constructor call is fine because True is of type bool, which is a subtype of int, and T can be instantiated to int. Thus, c should have type C[int]. This makes perfect sense and is totally natural if you write a bidirectional type checker anyway. Nothing controversial here.
What about the following?
c: C[bool] = ...
Does the type "widening" to the base type mentioned in the spec apply here too and this has to be interpreted as if the user had written C[int]? At least pyright interprets it this way. I'm wondering if this was the intent of the spec? Off the top of my head, I cannot think of a situation where this would be a useful feature (but I'm happy to convinced otherwise). Moreover, this can become rather counter-intuitive when C[bool] appears in contravariant positions.
I would like to get a conversation going that crystallizes the intent of the spec in this regard. If we come to a conclusion, I'd be more than happy to update the docs to reflect this outcome.
Here's how I would roughly specify the feature:
-
Explicit instantiations of constrained type variables via class/alias specializations must be taken at face value and not automatically be widened to base types. If the explicitly mentioned type argument is neither a type variable nor a type equivalent to one of the constraints, that's a type error. For the exact meaning of "equivalent", I would suggest to pick an equivalence relation on the more syntactic side of the spectrum of possibilities but haven't thought about this aspect too deeply so far.
-
Explicitly instantiating a constrained type variable
Twith another type variableSis only allowed ifSalso has constraints and each of them is also listed inT's constraints (up to the same equivalence as above). (I avoided the word "subset" on purpose since that's too easy to interpret as "subtype", which I do not mean!) -
All of this this should also apply to generic functions should there ever be a way to explicitly specialize them.
-
When inferring type arguments for generic function calls, including constructor calls, the function is conceptually "exploded" into an overloaded function with one case for each constraint and overload resolution decides which constraint to pick as the instantiation for the type variable.
This gets particularly gnarly in the presence of multiple matching constraints caused by multiple inheritance. Being consistent with overload resolution seems like a good property to have here.
This covers the covariant case illustrated in the example above where
boolgets "widened" toint. It also covers the contravariant case, where the functiondef higher_order[T: (int, str)](f: Callback[[T], None]): ...can be called with an argument of type
Callback[[float], None]andTgets instantiated toint. (In some sense,floatgets "narrowed" tointhere.)
- Linguagem predominante
- Python
- Estrelas
- 1.8k
- Forks
- 302
- Merge médio
- 4h 16min
- PRs com merge (30d)
- 7
Preparar o ambiente
Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de python/typing
-
topic: typing spec
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
python/typing#2356 · 2 comentários · 1 reação ·
Mantenedores costumam responder em até 1 dia
-
topic: typing spec
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
Mantenedores costumam responder em até 1 dia
-
topic: documentation
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
python/typing#2227 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
topic: documentation
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
python/typing#2150 · 2 comentários · 2 reações ·
Mantenedores costumam responder em até 1 dia
-
topic: conformance tests topic: typing spec
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 72/100
python/typing#2351 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
Todas as issues de python/typing
Issues semelhantes
-
#bug
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 92/100
apache/superset#44923 · 1 comentário ·
Mantenedores costumam responder em até 2 dias
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
lawndoc/stack-back#123 ·
-
Add: EntuneAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
AbdelStark/awesome-typesafe-jev#187 ·
Mantenedores costumam responder em até 1 dia
-
bug good first issue
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
repowise-dev/repowise#2966 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
Mantenedores costumam responder em até 2 dias