views:

127

answers:

3

Given a class such as

class MyClass:
    text = "hello"
    number = 123

Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the class I am to get it's attributes for are generate using SWIG (so they are hidden in .so :) ).

So I am really looking for something equivalant to Java's [Class.getDeclardFields][1]

Any help would be appreciated, otherwise I'll have to solve this problem with SWIG + JAVA instead of SWIG + Python.

+3  A: 

I usually just use dir(MyClass). Works on instantiated objects too.

edit: I should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically.

Also it may not work on linked libraries.

Garrett Bluma
I actually need it for linked libraries only
hhafez
Looks like ctypes doesn't fully support C++. Not sure if that's an issue for you but here's another good thread on it.http://stackoverflow.com/questions/135834/python-swig-vs-ctypes
Garrett Bluma
I'm using SWIG for C only, o it shouldn't be a problem
hhafez
A: 

Please write actual, executable code snippets; don't expect people answering your question to first fix your code.

class MyClass(object):
    text = "hello"
    number = 123

for a in dir(MyClass):
    print a
Glenn Maynard
big deal anyway, I only forgot a ':'
hhafez
@hhafez, you missed class too
Anurag Uniyal
I am not paying attention today
hhafez
A: 
>>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> cmath.atan
<built-in function atan>

is dirable and

open("/usr/lib/python2.6/lib-dynload/cmath.so", O_RDONLY) = 4
read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\17\0\0004\0\0\0"..., 512) = 512
fstat64(4, {st_mode=S_IFREG|0644, st_size=32176, ...}) = 0
mmap2(NULL, 43824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x268000
mmap2(0x26f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x6) = 0x26f000
mmap2(0x271000, 6960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x271000
close(4)

is dynamically loaded

msw