Parsing python/django code to make it editable in GUI

I'm developing a tool for creating/editing Django models, see https://github.com/timothyclemans/django-admin-models-editor.

What is the recommended way to parse Python code? Do I need to make a bunch of regular expressions and do a lot of if thens?

The code below get the model name and field names.

code_from_input = request.POST['code'].split('\n')[0]
def_lines = ''
if '    def' in request.POST['code']:
    for i, line in enumerate(request.POST['code'].split('\n')):
        if line.startswith('    def'):
            def_lines = '\n'.join(request.POST['code'].split('\n')[i:])
            break
last_code_from_input = request.POST['last_code'].split('\n')[0]
# check if model name in source changed
model_name_in_last_source = ''
model_name_in_code = ''
if last_code_from_input.startswith('class'):
    m = re.match(r"class (\w+)\(models.Model\):", last_code_from_input)
    try:
        model_name_in_last_source = m.group(1)
    except:
        pass
if code_from_input.startswith('class'):
    m = re.match(r"class (\w+)\(models.Model\):", code_from_input)
    try:
        model_name_in_code = m.group(1)
    except:
        pass
if model_name_in_last_source != model_name_in_code:
    model_name = model_name_in_code
else:
    model_name = request.POST['name']

Answers


For very simple use cases you could use regular expressions. If you just want to locate the classes inside the source, your approach is probably fine.

Alternatively, have a look at the inspect module, but this can only be used with imported python modules, not source files. You can enumerate the classes in your modules, extract method names, source code and documentation. This is probably the best approach for what you want.

http://docs.python.org/library/inspect.html

If you really delve deeper into the source, you might try the ast module. It provides a parse function that takes a string of python source and returns an abstract syntax tree. This is the most complex library, but also the most powerful.

See: http://docs.python.org/library/ast.html for more details.


Need Your Help

CSS: Different vertical alignments for a single <td>

html css table alignment center

I'm trying to create a table containing images in a gallery along with their names right below them. I'd like to center the images vertically in each column, and have the names aligned at the botto...

Adding .NET Framework DLL as reference to windows store app

c# .net windows-8 windows-store-apps labview

I'm working on a windows store app project where I want to read a simple temperature measurement data from a National Instruments DAQ. However the DLL library for the DAQ is in .NETFramework 4.0 fo...