How to find out the default values of a particular function's argument in another function in Python?

前端 未结 4 1775
野的像风
野的像风 2021-01-12 01:01

Let\'s suppose we have a function like this:

def myFunction(arg1=\'a default value\'):
  pass

We can use introspection to find out the name

4条回答
  •  无人及你
    2021-01-12 01:28

    As an alternative to rooting around in the attributes of the function you can use the inspect module for a slightly friendlier interface:

    For Python 3.x interpreters:

    import inspect
    spec = inspect.getfullargspec(myFunction)
    

    Then spec is a FullArgSpec object with attributes such as args and defaults:

    FullArgSpec(args=['arg1'], varargs=None, varkw=None, defaults=('a default value',), kwonlyargs=[], kwonlydefaults=None, annotations={})
    

    Some of these attributes are not available on Python 2 so if you have to use an old version inspect.getargspec(myFunction) will give you a similar value without the Python 3 features (getargspec also works on Python 3 but has been deprecated since Python 3.0 so don't use it):

    import inspect
    spec = inspect.getargspec(myFunction)
    

    Then spec is an ArgSpec object with attributes such as args and defaults:

    ArgSpec(args=['arg1'], varargs=None, keywords=None, defaults=('a default value',))
    

提交回复
热议问题