[Python] singledispatchmethod for list[str] or list[int]

Discussão em 'Python' iniciado por Stack, Julho 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to overload a method with singledispatchmethod. It works great for simple types like int and str, but for nested types like list[int], this breaks with the following error.

    TypeError: Invalid annotation for 'value'. list[int] is not a class.


    How can I handle this nested type when registering a specific-type method?

    I know there is an option for using the multimethod package, but I'm looking for a native base Python solution.

    from functools import singledispatchmethod

    class Processor:
    @singledispatchmethod
    def process(self, value):
    print(f"Default processing for {value}")

    @process.register
    def _(self, value: int):
    print(f"Processing an integer: {value}")

    @process.register
    def _(self, value: str):
    print(f"Processing a string: {value}")

    @process.register
    def _(self, value: list[int]):
    print(f"Processing a list of integers: {value}")

    @process.register
    def _(self, value: list[str]):
    print(f"Processing a list of strings: {value}")

    # Example usage:
    p = Processor()
    p.process(10) # Processing an integer: 10
    p.process("hello") # Processing a string: hello
    p.process([1, 2, 3]) # Processing a list: [1, 2, 3]
    p.process(["a", "b", "c"]) # Processing a list of strings: ['a', 'b', 'c']

    Continue reading...

Compartilhe esta Página