Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since you're talking about javascript and <code>hasattr</code>, I'm guessing this is a situation where <code>variable</code> is undefined. In Python, <code>hasattr</code> doesn't test for the presence of dictionary keys, it only tests for the presence of object attributes. Furthermore, there is no simpler way than <code>hasattr</code> to test whether an object has an attribute in Python, because unlike in javascript, variable names <em>must</em> be defined to be used. Therefore, to refer to a variable name that may or may not be defined, you must use a string. </p> <p>That said, you could use the ternary operator + <code>hasattr</code> to write the test in one line:</p> <pre><code>&gt;&gt;&gt; class F(object): ... pass ... &gt;&gt;&gt; f = F() &gt;&gt;&gt; f.foo = 5 &gt;&gt;&gt; f.bar if hasattr(f, 'bar') else 10 10 &gt;&gt;&gt; f.foo if hasattr(f, 'foo') else 10 5 </code></pre> <p>This works because <code>f.foo</code> isn't even evaluated if <code>hasattr</code> returns <code>False</code>.</p> <p>You could also define <code>f.foo = None</code> and use <code>or</code> as <a href="https://stackoverflow.com/questions/6697816/python-version-of-jss-x-variable-default-variable/6697904#6697904">Wooble</a> suggests in his comment.</p> <p>To test whether a key is in a dictionary, say <code>if k in d:</code>, and to get a default value if <code>k</code> isn't in the dictionary, if that's what you want, see <a href="https://stackoverflow.com/questions/6697816/python-version-of-jss-x-variable-default-variable/6697836#6697836">S.Lott's answer</a>.</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