473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

listing attributes

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

Feb 14 '06 #1
8 1663
Thomas Girod wrote:
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
Feb 14 '06 #2
Thomas Girod wrote:
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

Feb 14 '06 #3
On Feb.13 18h37, Thomas Girod wrote :
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
Feb 14 '06 #4
On Mon, 13 Feb 2006 22:18:56 -0500, Peter Hansen wrote:
Thomas Girod wrote:
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.)

class Parrot(object): .... 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

--
Steven.

Feb 14 '06 #5
Steven D'Aprano wrote:
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']
Feb 14 '06 #6
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.

Feb 14 '06 #7
Steven D'Aprano wrote:
On Mon, 13 Feb 2006 22:18:56 -0500, Peter Hansen wrote:
Thomas Girod wrote:
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.)

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.


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...)
class Parrot(object): .... ATTR = None
.... def method(self):
.... return None
.... polly = Parrot()
polly.foo = '1'
polly.bar = 'baz'
polly.__dict__

{'foo': '1', 'bar': 'baz'}

-Peter

Feb 14 '06 #8
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).

Feb 15 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Miguel Gonzalez | last post by:
Hello. Where could I find a table with all the CSS attributes and a list of its different values. Thanks.
19
by: SU News Server | last post by:
I've struggled with this for quite a while and I'm am just not sure what is going on. I have the following code import os def buildList( directory='/Users/mkonrad' ) dirs = listing =...
3
by: Rohit Sharma | last post by:
Hi all.. ..NET + MSXML platform....VB Need to build a list of all the entities and attributes to allow the user to do search...how can i do that from the schema ?? Cheers Rohit
3
by: David Jacques | last post by:
I am trying to get a list of all files of a certain extension type on disk to do some processing in a loop. The code needs to be portable to UNIX, so I need to use plain c functionality. Does...
2
by: Kurt Schroeder | last post by:
I have a simple directoy list bound to a datagrid. I can get the file names, but is there a way to get the file information from system.io.directory. I'd like to get file size, creation date, and...
1
by: vhg119 | last post by:
Can someone please link me to some resource listing all the user attributes names? I'm writing some C# code using the System.DirectoryServices assembly. This particular function is suppose to...
1
by: Johnny Jörgensen | last post by:
I've got a serious problem. I've got Visual Studio 2005 installed, and of course I'm using the Pretty Listing formatting function. When I start up VS, everything is fine, but after a while (which...
2
by: John Geddes | last post by:
If I create an object using a constructor function, and then specify attributes using the format "this.attrib1 = 123;" - then it is easy enough to list the VALUES (using a loop like "for thisAttrib...
5
by: jain236 | last post by:
HI every body, i am always getting the following error while parsing a directory . i am reading a directory by doing ls and trying to find out the name,type,size, mtime and mode of files from...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.