Search code examples
pythonabstract-syntax-tree

How to fetch line numbers for all 'if' 'else' and 'elif' positions in a python file


Example: Suppose, we have a .py file containing the below code snippet. How do we read and extract the positions of if-elif-else

If fisrtconditon:#line 1
    If sub-condition:#line2
       print(line no 3)
elif secnd_condn:#line 4
     Xyz..#line5
     Xyz..#line6
elif third condition:line7
     ...line 8
else:#line 9
    Some content #line10***

Output:

[1,4,7,9]

Solution

  • A simple solution is to iterate over the lines of the file, using enumerate to help you get the line number:

    with open("somefile.py") as f:
        for line_no, line in enumerate(f, start = 1):
            if line[:2] ==  "if" and (line[2].isspace() or line[2] == "("):
                print(line_no, "if")
            elif line[:4] == "elif" and (line[4].isspace() or line[4] == "("):
                print(line_no, "elif")
            elif line[:4] == "else" and (line[4].isspace() or line[4] == ":"):
                print(line_no, "else")
    

    Assumptions: this program assumes that somefile.py has correct syntax. Moreover, if this if statement appears indented, for example, inside a function definition, it would not work. The question's specifications did not dictate this requirement.

    This program

    • opens the file "somefile.py" for reading (the default mode of open);
    • iterates over the lines of the file, using enumerate to get an index; by default, indices will start from 0 but we specify the start parameter so that it starts from 1;
    • if the line starts with an if plus a (whitespace character or opening paren) or an elif plus a (whitespace character or opening paren) or an else plus a (colon : or a whitespace character), then we print the line number as well as the corresponding if, elif, or else.
    • as we exit the with block, Python closes the file for us.

    Example


    If somefile.py is

    if condition:
        if condition:
            something
    elif condition:
        something
        something
    elif condition:
        something
    else:
        something
    

    then the above program outputs

    1 if
    4 elif
    7 elif
    9 else