Reputation: 2064
Good day!
I'm writing a little tool that builds a GUI for my data-aware app.
The basic idea is to get a module containing a model description (sqla/elixir
entities) as an input, and to present the user with a list of available classes (inherited from Entity()
) and their fields (inherited from Field()
) from this module.
The pyclbr module is fine for getting classes and their methods, but it can't read other class-members. I know about __dict__
and inspect module, but the problem is they require instantiation of a class in question, and that is kind of wrong in this context. So, is there another way ?
I really don't want to parse modules as text. :)
Upvotes: 2
Views: 293
Reputation: 176780
I'm not sure I know what you mean:
class a(object):
b = 'a'
c = 'd'
print dir(a)
prints
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'b', 'c']
You can use
print [i for i in dir(a) if not i.endswith('__')]
if you don't want to see the special methods.
You don't need to instantiate the class to see it's members. You won't see attributes added inside methods, but everything defined in the class definition or a metaclass' __new__
method will be there.
See my answer to inspect.getmembers() vs __dict__.items() vs dir() for more info on what exactly these different functions return.
Upvotes: 5