Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

Python: check a function's default arguments

Given a function (e.g. 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...