How to use Python decorators to check function arguments?

后端 未结 8 1654
情歌与酒
情歌与酒 2020-11-28 22:56

I would like to define some generic decorators to check arguments before calling some functions.

Something like:

@checkArguments(types = [\'int\', \'         


        
8条回答
  •  Happy的楠姐
    2020-11-28 23:25

    I think the Python 3.5 answer to this question is beartype. As explained in this post it comes with handy features. Your code would then look like this

    from beartype import beartype
    @beartype
    def sprint(s: str) -> None:
       print(s)
    

    and results in

    >>> sprint("s")
    s
    >>> sprint(3)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 13, in func_beartyped
    TypeError: sprint() parameter s=3 not of 
    

提交回复
热议问题