Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if the next line should be indented when parsing python

I am writing a simple templating engine in python, and it involves mixing python with other languages, and I need to determine the indentation level of any given line of python code.

I was wondering if it's accurate to say that a new indentation level is always indicated by a colon (:) at the end of the line.

Here's a line of python:

if my_boolean:

Since there is a colon at the end of this line, I would determine that the next line of python should be an indented block. Is this always accurate? Are there cases when I need to indent when a colon is not present?

like image 784
Carsen Daniel Yates Avatar asked Dec 24 '18 04:12

Carsen Daniel Yates


1 Answers

A colon at the end of the line is the most prevalent example of an indicator that the following line is indented. The other one is any line that has more opening parentheses, braces, or brackets than closing ones. The latter case is more complicated because the order of the brackets matters very much, and also because the following indentation is arbitrary.

Another thing to consider is that you don't have any indication that wether a given line is expected to be unindented until you get to it.

The moral of the story is that you're better off using the existing machinery exposed by the ast module rather than reinventing the wheel. It's an awfully complicated wheel sometimes.

like image 104
Mad Physicist Avatar answered Sep 29 '22 08:09

Mad Physicist