Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This will print names of all passable arguments, keyword and non-keyword ones:</p> <pre><code>def func(one, two="value"): y = one, two return y print func.func_code.co_varnames[:func.func_code.co_argcount] </code></pre> <p>This is because first <code>co_varnames</code> are always parameters (next are local variables, like <code>y</code> in the example above).</p> <p>So now you could have a function:</p> <pre><code>def getValidArgs(func, argsDict): '''Return dictionary without invalid function arguments.''' validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] return dict((key, value) for key, value in argsDict.iteritems() if key in validArgs) </code></pre> <p>Which you then could use like this:</p> <pre><code>&gt;&gt;&gt; func(**getValidArgs(func, args)) </code></pre> <hr> <p><strong>EDIT</strong>: A small addition: if you <strong>really need only keyword arguments</strong> of a function, you can use the <code>func_defaults</code> attribute to extract them:</p> <pre><code>def getValidKwargs(func, argsDict): validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] kwargsLen = len(func.func_defaults) # number of keyword arguments validKwargs = validArgs[-kwargsLen:] # because kwargs are last return dict((key, value) for key, value in argsDict.iteritems() if key in validKwargs) </code></pre> <p>You could now call your function with known args, but extracted kwargs, e.g.:</p> <pre><code>func(param1, param2, **getValidKwargs(func, kwargsDict)) </code></pre> <p>This assumes that <code>func</code> uses no <code>*args</code> or <code>**kwargs</code> magic in its signature.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload