python / python/mypy

Multi-level type resolution

Aperta
#10,164 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature priority-2-low
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Feature

It would be nice if Mypy was able to resolve the types in the below snippet:

import os
import typing as t
T = t.TypeVar('T')
R = t.TypeVar('R')

class flatmap(t.Generic[T, R]):

  def __init__(self, func: t.Callable[[T], R]) -> None:
    self.func = func

  def __ror__(self, value: t.Optional[T]) -> t.Optional[R]:
    if value is not None:
      return self.func(value)
    return None

# error: Cannot infer type argument 1 of "flatmap"
# error: "object" has no attribute "upper"
print(os.getenv('VARNAME') | flatmap(lambda m: m.upper()))
print(os.getenv('VARNAME') | flatmap(str.upper))  # ok

Pitch

Looking at just flatmap(lambda m: m.upper()), neither T nor R can be immediately determined.
However, it should be possible to deduce the type variables by taking into account the broader
context.

  • T = str can be derived from the __ror__() call
  • After propagating T into the flatmap() and lambda, R = str can be deduced from the lambda body

One potential use case is already highlighted in the example above. Being able to chain the flatmap() function using ror adds a lot of readability compared to a normal call:

# 1)
os.getenv('VARNAME') | flatmap(lambda m: m.upper())

# 2)
flatmap(os.getenv('VARNAME'), lambda m: m.upper())

The obvious workaround in this example would be to use str.upper which would satisfy Mypy because the function is already typed. However, there are other example where the there is no already-typed alternative, like accessing an attribute of an optional object. Nr. 1 would be preferred over 2 for it's better readability. 3 is an alternative without a helper function, though that also gets harder to read as you start to work with more optional values.

# 1)
email = maybe_get_user() | flatmap(lambda user: user.email) | flatmap(sanitize_email_address)

# 2)
email = flatmap(flatmap(maybe_get_user(), lambda user: user.email), sanitize_email_address)

# 3)
user = maybe_get_user()
email = sanitize_email_address(user.email) if user and user.email else None

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci il problema con lo snippet Python fornito e confronta il caso lambda con il caso funzionante di str.upper. Traccia la gestione da parte di mypy della costruzione generica di flatmap, della chiamata a ror e della propagazione attraverso lambda; il lavoro è completato quando gli esempi inferiscono i risultati Optional[str] attesi senza errori.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.