1

I have an application that embeds python and exposes its internal object model as python objects/classes.

For autocompletion/scripting purposes I'd like to extract a mock of the inernal object model, containing the doc tags, structure, functions, etc so I can use it as library source for the IDE autocompletion.

Does someone know of a library, or has some code snippet that could be used to dump those classes to source?

Ramon Poca
  • 1,889
  • 1
  • 10
  • 19

2 Answers2

2

Use the dir() or globals() function to get the list of what has been defined yet. Then, to filter and browse your classes use the inspect module

Example toto.py:

class Example(object):
    """class docstring"""

    def hello(self):
        """hello doctring"""
        pass

Example browse.py:

import inspect
import toto

for name, value in inspect.getmembers(toto):
    # First ignore python defined variables
    if name.startswith('__'):
        continue

    # Now only browse classes
    if not inspect.isclass(value):
        continue
    print "Found class %s with doctring \"%s\"" % (name, inspect.getdoc(value))

    # Only browse functions in the current class
    for sub_name, sub_value in inspect.getmembers(value):
        if not inspect.ismethod(sub_value):
            continue
        print "  Found method %s with docstring \"%s\"" % \
            (sub_name, inspect.getdoc(sub_value))

python browse.py:

Found class Example with doctring "class docstring"
  Found method hello with docstring "hello doctring"

Also, that doesn't really answer your question, but if you're writing a sort of IDE, you can also use the ast module to parse python source files and get information about them

Scout
  • 550
  • 2
  • 5
0

Python data structures are mutable (see What is a monkey patch?), so extracting a mock would not be enough. You could instead ask the interpreter for possible autocompletion strings dynamically using the dir() built-in function.

Community
  • 1
  • 1
utapyngo
  • 6,946
  • 3
  • 44
  • 65
  • In this case a mock would be enough. I cannot ask the interpreter because it's compiled into the executable, but I can make it execute a script to dump the internal classes. – Ramon Poca Apr 29 '13 at 11:20
  • @RamonPoca, I don't understand you. Even if the interpreter is embedded and compiled, it is still the interpreter. Please clarify your question, maybe with some code samples. – utapyngo Apr 29 '13 at 15:39
  • Plus presumably if the user can access the interpreter, so can the application? – Felipe Apr 29 '13 at 16:38