Is there a way to check a function's signature in Python?

后端 未结 4 2361
我寻月下人不归
我寻月下人不归 2021-02-19 08:16

I\'m looking for a way to check the number of arguments that a given function takes in Python. The purpose is to achieve a more robust method of patching my classes for tests.

相关标签:
4条回答
  • 2021-02-19 08:27

    You should use inspect.getargspec.

    0 讨论(0)
  • 2021-02-19 08:28

    inspect.getargspec is deprecated in Python 3. Consider something like:

    import inspect
    len(inspect.signature(foo_func).parameters)
    
    0 讨论(0)
  • 2021-02-19 08:31

    The inspect module allows you to examine a function's arguments. This has been asked a few times on Stack Overflow; try searching for some of those answers. For example:

    Getting method parameter names in python

    0 讨论(0)
  • 2021-02-19 08:45

    You can use:

    import inspect
    len(inspect.getargspec(foo_func)[0])
    

    This won't acknowledge variable-length parameters, like:

    def foo(a, b, *args, **kwargs):
        pass
    
    0 讨论(0)
提交回复
热议问题