python / python/typing

Callable with variadic fixed arguments that doesn't mean *args

Aperta
#1,301 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic: other
Lingua principale
Python
Stelle
1.8k
Fork
302
Merge medio
23h
PR unite (30g)
8

Descrizione

Suppose I have a type of function called CommandHandler, that is a function that receives a command as its first parameter but then could have other parameters.
Examples

class Command:
    pass

class RegisterUser(Command):
    pass

class DeleteUser(Command):
    pass

def register_user(command: RegisterUser, db : Db) -> None:
    ...

def delete_user(command: DeleteUser, dispatch: EventDispatcher, cache: Cache) -> None:
    ...

mappings : dict[Command, CommandHandler] = {
    RegisterUser: register_user,
    DeleteUser: delete_user
}

What would be the definition of CommandHandler?

Ideally it would be:

C= TypeVar("C", bound=Command)
CommandHandler = Callable[[C, ...], None] 

But this syntax is not possible.

I've found in the documentation that Concatenate could receive ... at the end,

Concatenate is currently only valid when used as the first argument to a Callable. The last parameter to Concatenate must be a ParamSpec or ellipsis (...).

so it could be:

C= TypeVar("C", bound=Command)
CommandHandler = Callable[Concatenate[C, ...], None] 

But this returns an error from Pylance:

image

One could say Callback Protocol could solve this like:

C= TypeVar("C", bound=Command)
class CommandHandler(Protocol):
    def __call__(self, __command: C, *__args: Any) -> None: ...

But it only receives functions that has an implicit variadic argument, it doesn't work with variadic forms of the function.

So far the only way I could solve this is through the Union of many Callables, but it doesn't look like the best solution.

At the end CommandHandler can only be defined as:

C= TypeVar("C", bound=Command)
CommandHandler = Union[
    Callable[[C, Any], None],
    Callable[[C, Any, Any], None],
    Callable[[C, Any, Any, Any], None],
    Callable[[C, Any, Any, Any, Any], None],
    Callable[[C, Any, Any, Any, Any, Any], None],
    Callable[[C, Any, Any, Any, Any, Any, Any], None],
    Callable[[C, Any, Any, Any, Any, Any, Any, Any], None],
    Callable[
        [C, Any, Any, Any, Any, Any, Any, Any, Any], None
    ],
]

Related:
https://github.com/python/cpython/issues/88954
https://stackoverflow.com/questions/57658879/python-type-hint-for-callable-with-variable-number-of-str-same-type-arguments

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

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

Inizia con la documentazione di Callable e Concatenate descritta nell’issue, quindi esamina l’issue correlata 88954 e la discussione collegata su Stack Overflow. Confronta le forme di CommandHandler richieste con le regole di typing attuali e determina se un design supportato può esprimerle; il lavoro completato deve includere una specifica concordata e un piano corrispondente per la documentazione o l’implementazione.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.