Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://docs.python.org/library/functions.html#locals" rel="noreferrer"><code>locals()</code></a> may be your friend here if you call it first thing in your function.</p> <p><strong>Example 1</strong>:</p> <pre><code>&gt;&gt;&gt; def fun(a, b, c): ... d = locals() ... e = d ... print e ... print locals() ... &gt;&gt;&gt; fun(1, 2, 3) {'a': 1, 'c': 3, 'b': 2} {'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}} </code></pre> <p><strong>Example 2</strong>:</p> <pre><code>&gt;&gt;&gt; def nones(a, b, c, d): ... arguments = locals() ... print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None) ... &gt;&gt;&gt; nones("Something", None, 'N', False) The following arguments are not None: a, c, d </code></pre> <p><strong>Answer</strong>:</p> <pre><code>&gt;&gt;&gt; def foo(a, b, c): ... return ''.join(v for v in locals().values() if v is not None) ... &gt;&gt;&gt; foo('Cleese', 'Palin', None) 'CleesePalin' </code></pre> <p><strong>Update</strong>:</p> <p>'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the <code>dict</code> returned by <code>locals()</code> (or <code>vars()</code>) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:</p> <pre><code>&gt;&gt;&gt; def foo(a, b, c): ... arguments = locals() ... return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None) ... &gt;&gt;&gt; foo(None, 'Antioch', 3) 'Antioch3' </code></pre>
 

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