tags:

views:

95

answers:

1

Dear stackoverflow-

My goal is to parse a class and return a data-structure (object, dictionary, etc) that is descriptive of the methods and the related parameters contained within the class. Bonus points for types and returns...

Requirements: Must be Python

For example, the below class:

class Foo:
    def bar(hello=None):
         return hello

    def baz(world=None):
         return baz

Would be parsed to return

result = {class:"Foo", 
          methods: [{name: "bar", params:["hello"]}, 
                    {name: "baz", params:["world"]}]}

So that's just an example of what I'm thinking... I'm really flexible on the data-structure.

Any ideas/examples on how to achieve this?

+8  A: 

You probably want to check out Python's inspect module. It will get you most of the way there:

>>> class Foo:
...     def bar(hello=None):
...          return hello
...     def baz(world=None):
...          return baz
...
>>> import inspect
>>> members = inspect.getmembers(Foo)
>>> print members
[('__doc__', None), ('__module__', '__main__'), ('bar', <unbound method Foo.bar>
), ('baz', <unbound method Foo.baz>)]
>>> inspect.getargspec(members[2][1])
(['hello'], None, None, (None,))
>>> inspect.getargspec(members[3][1])
(['world'], None, None, (None,))

This isn't in the syntax you wanted, but that part should be fairly straight forward as you read the docs.

Paolo Bergantino
`inspect` looks just like what you're looking for. For a more low-tech solution, you can just take a look at `Foo.__dict__` which contains most (all?) of `class Foo`'s members.
Mike Mazur
...and also `Foo.__name__` to get the name of the class. Useful when you're passed an object which contains a class.
Mike Mazur