How to get selected attributes of an object in to a python list?
<p>How do I create a list with the selected attributes of an object in python ? Using list comprehensions.</p>

<p>E.g: </p>

<p>My object A has</p>

<pre><code>A.name
A.age
A.height
</code></pre>

<p>and many more attributes</p>

<p>How do I create a list <code>[name,age]</code></p>

<p>I can do it manually but it looks ugly:</p>

<pre><code>l=[]
l.append(A.name)
l.append(A.age)
</code></pre>

<p>but I am looking for a shortcut.</p>

<p>You can collect them going through all <code>A</code> class attributes and checking if they aren't method or built-in.</p>

<pre><code>import inspect

def collect_props():
    for name in dir(A):
        if not inspect.ismethod(getattr(A, name)) and\
           not name.startswith('__'):
            yield name

print list(collect_props())
</code></pre>

python list list-comprehension python-2.x