[Python] Is it possible to unpack a list of classes for use in a Union type annotation?...

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a number of SQLAlchemy ORM classes that map to a database. I've written quite a few functions that utilise a number of these classes in different combinations. For example I might want to get the first from the Tournament table or the first record from the Player table. I only need one query for this as the queried fields are the same between the tables. To maintain type hints I could do the following:

    def get_first_record(table: Type[Union[Tournament, Player]]):
    # query the table for the first record


    If I don't want to keep repeating the type hint for other functions then I could create a variable:

    Tables = Type[Union[Tournament, Player]]

    def get_last_record(table: Tables):
    # query the table for the last record


    As I have a large number of tables and add to them frequently then it's a pain to maintain these Union variables.

    Coincidentally for locking and unlocking certain combinations of tables I've written some functions to create custom lists of classes in modules. I was hoping to be able to unpack these lists when creating the Union variables but Pylance tells me Union needs more than two variables:

    tables = [Tournament, Player]
    Tables = Type[Union[*tables]] # no bueno :(


    Is there a solution to this?

    Continue reading...

Compartilhe esta Página