4

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?

cdleary
  • 69,512
  • 53
  • 163
  • 191
roder
  • 566
  • 6
  • 13
  • looks question http://stackoverflow.com/questions/990016/how-to-find-out-the-arity-of-a-method-in-python, it contains what you will need and also explains what you can't do – Anurag Uniyal Jul 04 '09 at 04:21

1 Answers1

8

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
  • 480,997
  • 81
  • 517
  • 436
  • 1
    `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 Jul 04 '09 at 03:16
  • 1
    ...and also `Foo.__name__` to get the name of the class. Useful when you're passed an object which contains a class. – Mike Mazur Jul 04 '09 at 03:18