-1

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

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • Just found https://stackoverflow.com/questions/12627118/get-a-function-arguments-default-value, where the OP is trying to author a function in a way such that its default values can be checked externally. So I guess it's impossible to check a function's default arguments in general then? It'll be nice if someone can confirm. – kgf3JfUtW Jan 16 '19 at 07:31
  • 1
    Does `help(ec2.create_instances)` show anything? – 9769953 Jan 16 '19 at 07:33
  • @9769953 Yes, it shows the full documentation as presented on the website. I just found `:type MaxCount: integer :param MaxCount: **[REQUIRED]**` in that documentation. Thanks! Still wondering if this can be done in general though (i.e. in the absence of documentation). – kgf3JfUtW Jan 16 '19 at 07:36
  • 4
    If an argument is just `**kwargs`, you should look at the source code to see how things are dealt with. But in this case, the documentation actually states what the default value is for some of the arguments. And technically, there are no default arguments for this function. – 9769953 Jan 16 '19 at 07:37
  • `help(function)` will always give you the function signature; it doesn't matter if there is a doc-string or not. So that works in general. – 9769953 Jan 16 '19 at 07:40

1 Answers1

3

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301