Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does Python look for __members__ rather than the requested field?
    text
    copied!<p>I have a class that defines its own <code>__getattr__()</code> in order to interact with an XML tree instantiated objects contain. This hides the XML structure from the user and allows him to set tag values, etc. as if they were normal fields on the object and works fine for all fields except for one: The one named <code>field</code>. Here's how it looks:</p> <pre><code>&gt;&gt;&gt; q = MyQuery() &gt;&gt;&gt; q.file = "database" &gt;&gt;&gt; print(q) &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;requestCollection xmlns="http://dwd.de/sky"&gt; &lt;read&gt; &lt;select&gt; &lt;referenceDate&gt; &lt;value&gt;&lt;/value&gt; &lt;/referenceDate&gt; &lt;/select&gt; &lt;transfer&gt; &lt;file name="my file"/&gt; &lt;/transfer&gt; &lt;/read&gt; &lt;/requestCollection&gt; &gt;&gt;&gt; q.file </code></pre> <p>That works fine, the side effects that should happen do so. But if I try to set the field <code>field</code>, I get a string that the method shouldn't be returning. For clarity, this is a simplified version of my <code>__getattr__</code>:</p> <pre><code>def __getattr__(self, key): logging.info("Looking up value for key {}.".format(key)) if key == "something" return self.method_with_side_effect(key) if key in field_list: logging.info("Key is in the field list.") return self.other_method_with_side_effects(key) </code></pre> <p><code>ensemble_member</code> and <code>field</code> are both in <code>field_list</code>. Check this out:</p> <pre><code>&gt;&gt;&gt; q = MyQuery() &gt;&gt;&gt; q.ensemble_member Looking up value for key __members__. Looking up value for key __methods__. Looking up value for key ensemble_member. Key is in the field list. ... Side effects ... &gt;&gt;&gt; q.field 'station' Looking up value for key __members__. Looking up value for key __methods__. </code></pre> <p>The behavior for <code>ensemble_member</code> is correct, for <code>field</code> it's totally incorrect. Why is that?</p> <p>I have no methods nor class / object members named <code>field</code>.</p> <p>Another interesting thing is, if I put this on the first line of <code>__getattr__</code>:</p> <pre><code>def __getattr__(self, key): if key == "field": raise ValueError </code></pre> <p>The following still happens:</p> <pre><code>&gt;&gt;&gt; q = MyQuery() &gt;&gt;&gt; q.field 'station' Looking up value for key __members__. Looking up value for key __methods__. </code></pre> <p>What's going on?</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