简体   繁体   中英

Python: check a function's default arguments

Given a function (eg create_instances ) which takes many keyword arguments, how do I know which arguments have default values, and what exactly are the default values?


To give full context, I'm using the boto3 AWS Python API:

import boto3
ec2 = boto3.resource('ec2')
ec2.create_instances( ... )

For example, the create_instances function takes an argument MaxCount , but I want to know whether it has a default value. I looked around in the inspect module but wasn't did not find anything useful.

The documentation of create_instances is at https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances

inspect.getfullargspec(ec2.create_instance) should normally give you everything you need. Align args and defaults on the right side. For example:

def foo(a, b=3, *c, d=5):
    m = a + b
    return m

argspec = inspect.getfullargspec(ec2.create_instance)
{**dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults)),
 **argspec.kwonlydefaults}
# => {'b': 3, 'd': 5}

As @9769953 says, if a parameter is bundled in **kwargs , it is processed by the function's code, and is thus not found in the function signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM