Python: Discover acceptable keyword arguments

Viewed 57

In many packages documentation, you can read something like bellow from matplotlib:

fig.colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)

How can one know what are the other possibilities with **kw? Some documentations describe them others don't.

2 Answers

There is no way to find them without documentation OR looking at the code. **kwargs is a dictionary, so searching for kwargs[ with your editor (Ctrl+F) inside the source code should reveal all used keys, and then you can figure out usage by name and how they are used inside of the code, but most of the time the name alone is self documenting.

There is no way to directly find them because the compiler doesnt track them, for the compiler its just a fancy way to pass a dictionary, and the program doesnt fail if you pass any unexpected kwargs

Directly you can't, but you may guess **kargs keys, which have been used inside the function.

def func(**kargs):
  c1 = kargs['key']
  c2 = kargs['key2']
  kargs[1] = 2

print(func.__code__.co_consts)

[None, 'key', 'key2', 1, 2]

You can use it with, inspect.getsource

import inspect
# get function body
inspect.getsource(func).split('\n')

It might not work, for modules optimized, using cython, or written in C Python API.

Related