2

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.

BND
  • 612
  • 1
  • 13
  • 23
  • 1
    The point of kwargs is that it will take anything. Often those are just passed through untouched, on purpose -- they are not used by that code, but might be used by other things. If the code uses one and doesn't document it, then I guess you would have to look at the code to discover that? Here is as close as I could find: https://stackoverflow.com/questions/36802469/any-way-to-find-all-possible-kwargs-for-a-function-in-python-from-cli – Kenny Ostrom Jul 04 '20 at 16:56
  • I think this question / answer is a superset: https://stackoverflow.com/questions/218616/how-to-get-method-parameter-names – Dylan McNamee Jul 04 '20 at 18:34

2 Answers2

2

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

DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
1

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.

4.Pi.n
  • 1,151
  • 6
  • 15