Decorator for overloading in Python

前端 未结 3 1511
礼貌的吻别
礼貌的吻别 2020-12-15 00:47

I know it\'s not Pythonic to write functions that care about the type of the arguments, but there are cases when it\'s simply impossible to ignore types because they are han

3条回答
  •  不思量自难忘°
    2020-12-15 01:08

    Since Python 3.4 the functools module now supports a @singledispatch decorator. In your case this would look like:

    from functools import singledispatch
    
    
    @singledispatch
    def func(val):
        raise NotImplementedError
    
    
    @func.register
    def _(val: str):
        print('This is a string')
    
    
    @func.register
    def _(val: int):
        print('This is an int')
    

    Usage

    func("test") --> "This is a string"
    func(1) --> "This is an int"
    func(None) --> NotImplementedError
    

提交回复
热议问题