简体   繁体   中英

Embedded python interpreter, generate stub source code for autocompletion

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM