Any way to find all possible kwargs for a function in python from cli?
Asked Answered
P

2

10

Is there a way to discover the potential keyword arguments for a function in python from the command line? without looking at the source or docs. Sometimes the source is to c lib even that isn't visible

Publishing answered 22/4, 2016 at 20:6 Comment(2)
help(whatever_function)?Fornof
By definition every possible key value pair is a potential keyword argument if you use kwargsMurk
S
5

You can use the inspect module. In 3.3+, this is easy by using inspect.signature

import inspect

def foo(bar=None, baz=None):
    pass

>>> print(inspect.signature(foo))
(bar=None, baz=None)

Immediately underneath the linked doc is an example that pulls out only the names of the keyword-only arguments, which may be worth reading too!

Of course if you're looking to deep inspect the source code to try and find anything that is pulled out of a **kwargs argument, you're probably out of luck. Something like:

def foo(**kwargs):
    if kwargs.get("isawesome"):
        print("Dang you're awesome")

>>> some_magic(foo)
isawesome

is probably going to be hard to find.

Seema answered 22/4, 2016 at 20:12 Comment(2)
Note also that this won't work for all builtin functions written in C, which don't usually have named arguments at all: E.g., try inspect.signature(sum) and you'll get an error.Shire
A good point! I don't know if there's any way to inspect the signature of a function that's not written in Python.Seema
S
1

For a function 'myfunc' use this:

myfunc.__code__.co_varnames
Seidel answered 5/6, 2021 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.