tags:

views:

127

answers:

4

I have this class definition:

class cols:
    name = 'name'
    size = 'size'
    date = 'date'
    @classmethod
    def foo(cls):
        print "This is a class method"

With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only the class variables without instantiation?

A: 
import inspect
inspect.getmembers(cols)

There are a lot if things you can do with the inspect module: http://lfw.org/python/inspect.html

jcoon
inspect.getmembers just returns whatever dir() returns, which is not what the OP asked.
Torsten Marek
+2  A: 

I wouldn't know a straightforward way, especially since from the interpreter's POV, there is not that much of a difference between a method of a class and any other variable (methods have descriptors, but that's it...).

So when you only want non-callable class members, you have to fiddle around a little:

>>> class cols:
...     name = "name"
...     @classmethod
...     def foo(cls): pass

>>> import inspect
>>> def get_vars(cls):
...     return [name for name, obj in cls.__dict__.iteritems()
                if not name.startswith("__") and not inspect.isroutine(obj)]
>>> get_vars(cols)
['name']
Torsten Marek
A: 

But with inspect.getmembers I get my function foo listed too. The getmembers function have a second (optional) parameter for the type of member to be retrieved (i.e.: inspect.ismethod) but I can't find something like inspect.isattribute.

Thank you in advance.

Don't comment on answers with an answers, that's what the comments are for. Doing something like is is likely to get voted down quickly in the more populated parts of SO!
Torsten Marek
Ah, should've realized, you can't comment yet... That's somewhat of a flaw in the system.
Torsten Marek
A: 

Torsten you're right twice. First with your answer (you wrote the code I need) and second with your comment about my lack of comment capability (I tried to comment the coonj answer but I don't have any reputation yet).

Thank you.

Well, accepting my answer will give you 2 rep points, which is just what you need to upvote. A couple more questions or answers, you'll be at 50 and can comment!
Torsten Marek