[Python] Typed python Capitalize Literals

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to do the python equivalent of the following typescript type.

    type EventsTypes = 'click' | 'touch';
    type EventHandlers = `on${Capitalize<EventsTypes>}`; // 'onClick' | 'onTouch'


    I read through https://docs.python.org/3/library/typing.html and there doesn't seem to be a built-in way so I tried the following

    import typing
    @typing._SpecialForm
    def Capitalize(self,*parameters):
    args = [p.title() for p in typing._flatten_literal_params(parameters)]
    return typing.Literal[*args]

    @typing._SpecialForm
    def Concat(self,parameters):
    prepend = parameters[0]
    types = parameters[1:]
    args = [prepend+p for p in typing._flatten_literal_params(types)]
    return typing.Literal[*args]

    EventTypes = typing.Literal['click','touch']
    EventsCapitalized = Capitalize[EventTypes]
    print(EventsCapitalized) #typing.Literal["Click","Touch"] however, vscode on hover over EventsCapitalized says the type is object
    EventHandlers = Concat["on",Capitalize[EventTypes]]
    print(eventHandlers) #typing.Literal["onClick","onTouch"] however, vscode on hover over EventHandlers says the type is object


    I was hoping that someone has solved this before.

    Continue reading...

Compartilhe esta Página