listing attributes

T

Thomas Girod

Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?

Thanks

Thomas
 
E

Evan Monroig

Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

If you do something like this you should have a list of attributes:

l = dir(object)
l = [s for s in l if s[:2] != '__']
l = [s for s in l if not callable(getattr(object, s))]

cheers,

Evan
 
J

James Stroud

Thomas said:
Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?

Thanks

Thomas


Here's a "smart-ass" example:

py> import random
py> class C:
.... def __repr__(self):
.... return "<Im_a_C!>"
....
py> alist = [1,2,3,4,5] + [C() for x in xrange(5)]
py> alist
[1, 2, 3, 4, 5, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]
py> class Obj:
.... def __repr__(self):
.... return str([getattr(self, o) for o in dir(self) \
.... if isinstance(getattr(self, o), C)])
....
py> anobj = Obj()
py> newlist = [choice(alist) for x in xrange(10)]
py> newlist
[<Im_a_C!>, <Im_a_C!>, 5, 1, 5, 4, 4, <Im_a_C!>, <Im_a_C!>, 3]
py> [setattr(anobj, *tup) for tup in zip('abcdefghij', newlist)]
[None, None, None, None, None, None, None, None, None, None]
py> anobj.a
<Im_a_C!>
py> anobj.b
<Im_a_C!>
py> anobj.c
5
py> anobj.d
1
py> print anobj
[<Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]

James
 
P

Peter Hansen

Thomas said:
I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?

Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__.keys() would be just the names of those attributes.)

-Peter
 
S

Steven D'Aprano

Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__.keys() would be just the names of those attributes.)
.... ATTR = None
.... def method(self):
.... return None
....
dir(Parrot) ['ATTR', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'method']
Parrot.__dict__.keys()
['__module__', 'ATTR', 'method', '__dict__', '__weakref__', '__doc__']

So I guess the answer to that question is, while __dict__ gives less
information than dir, it still gives too much.

The thing to remember is that methods are attributes too, so it is a
little hard to expect Python to magically know which attributes you want
to see and which you don't. Although, I don't think it is too much to
expect Python to distinguish methods from non-method attributes.

However it is easy to use introspection to get what you need.

def introspect(obj):
attributes == dir(obj)
# get rid of attributes that aren't the right type
attributes = [a for a in attributes if \
type(getattr(obj, a)) == type(obj)]
# or filter any other way you like
return attributes
 
C

Christoph Zwerschke

Steven said:
> However it is easy to use introspection to get what you need.

So just for completeness sake, what Thomas probably wants is the following:

from types import MethodType

def attributes(obj):
return [attr for attr in dir(obj)
if not attr.startswith('__')
and not isinstance(getattr(obj, attr), MethodType)]

# Example:

class Parrot(object):
ATTR = None
join = ''.join # callable, but not a method of Parrot
def aMethod(self):
return ATTR

print attributes(Parrot)

# this gives: ['ATTR', 'join']
 
T

Thomas Girod

Thanks a lot for all your answers !

Thanks to you I resolved this problem. Here is what i've done :

[...]
for (_,v) in getmembers(self):
if isinstance(v,Property):
st += "\t%s\n" % str(v)
[...]

as all the attributes I want to get are instances of Property or a
subclass of Property, it does the trick.
 
P

Peter Hansen

Steven said:
Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__.keys() would be just the names of those attributes.)

['__module__', 'ATTR', 'method', '__dict__', '__weakref__', '__doc__']

So I guess the answer to that question is, while __dict__ gives less
information than dir, it still gives too much.

I was making the perhaps mistaken assumption that the OP was another of
those who meant "object" when he said "class" (though I could perhaps
have asked that explicitly).

If that were the case, I think __dict__ could be what he wanted. (I'm
still not sure what he wanted, even after reading his response, since I
can't see what his classes or objects look like...)
.... ATTR = None
.... def method(self):
.... return None
....{'foo': '1', 'bar': 'baz'}

-Peter
 
T

Thomas Girod

You are right, using __dict__ is what i needed.

But I chose the solution explained before because i don't want to list
all attributes of the object, only attributes that are instances of the
class Property (or a subclass of it).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top