Avoid extra line for attribute check?
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p>

<p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>).
Here is an example list.</p>

<pre><code>ins_list = [ins_1, ins_2, None, ins_3, None]
</code></pre>

<p>I have to do some confirmations throughout the program flow. There are points where I need the control an attribute of these instances. But only indexes are given for choosing an instance from the list and it may be one of the empty elements. Which would give an error when the attribute is called. Here is an example program flow.</p>

<pre><code>ind = 2

if ins_list[ind].some_attribute == "thing":
    # This would give error when empty element is selected.
</code></pre>

<p>I deal with this by using,</p>

<pre><code>if ins_list[ind]:
    if ins_list[ind].some_attribute == "thing":
        # This works
</code></pre>

<p>I am okay with using this. However the program is a long one, I apply this hundreds of times. Is there an easier, better way of doing this, it means I am producing reduntant code and increasing indentation level for no reason. I wish to know if there is such a solution.</p>

<p>As coder proposed, you can remove None from your list, or use dictionaries instead, to avoid to have to create an entry for each index.</p>

<p>I want to propose another way: you can create a dummyclass and replace None by it. This way there will be no error if you set an attribute:</p>

<pre><code>class dummy:
    def __nonzero__(self):
        return False
    def __setattr__(self, k, v):
        return


mydummy = dummy()
mylist = [ins_1, ins_2, mydummy, ins_3, mydummy]
</code></pre>

<p>nothing will be stored to the dummyinstances when setting an attribute</p>

<p><strong>edit:</strong></p>

<p>If the content of the original list cannot be chosen, then this class could help:</p>

<pre><code>class PickyList(list):
    def __init__(self, iterable, dummyval):
        self.dummy = dummyval
        return super(PickyList, self).__init__(iterable)
    def __getitem__(self, k):
        v = super(PickyList, self).__getitem__(k)
        return (self.dummy if v is None else v)



mylist = PickyList(ins_list, mydummy)
</code></pre>

python attributes