Can a line of Python code know its indentation nesting level?

前端 未结 5 724
失恋的感觉
失恋的感觉 2021-01-30 07:40

From something like this:

print(get_indentation_level())

    print(get_indentation_level())

        print(get_indentation_level())

I would li

5条回答
  •  你的背包
    2021-01-30 08:26

    You can use sys.current_frame.f_lineno in order to get the line number. Then in order to find the number of indentation level you need to find the previous line with zero indentation then be subtracting the current line number from that line's number you'll get the number of indentation:

    import sys
    current_frame = sys._getframe(0)
    
    def get_ind_num():
        with open(__file__) as f:
            lines = f.readlines()
        current_line_no = current_frame.f_lineno
        to_current = lines[:current_line_no]
        previous_zoro_ind = len(to_current) - next(i for i, line in enumerate(to_current[::-1]) if not line[0].isspace())
        return current_line_no - previous_zoro_ind
    

    Demo:

    if True:
        print get_ind_num()
        if True:
            print(get_ind_num())
            if True:
                print(get_ind_num())
                if True: print(get_ind_num())
    # Output
    1
    3
    5
    6
    

    If you want the number of the indentation level based on the previouse lines with : you can just do it with a little change:

    def get_ind_num():
        with open(__file__) as f:
            lines = f.readlines()
    
        current_line_no = current_frame.f_lineno
        to_current = lines[:current_line_no]
        previous_zoro_ind = len(to_current) - next(i for i, line in enumerate(to_current[::-1]) if not line[0].isspace())
        return sum(1 for line in lines[previous_zoro_ind-1:current_line_no] if line.strip().endswith(':'))
    

    Demo:

    if True:
        print get_ind_num()
        if True:
            print(get_ind_num())
            if True:
                print(get_ind_num())
                if True: print(get_ind_num())
    # Output
    1
    2
    3
    3
    

    And as an alternative answer here is a function for getting the number of indentation (whitespace):

    import sys
    from itertools import takewhile
    current_frame = sys._getframe(0)
    
    def get_ind_num():
        with open(__file__) as f:
            lines = f.readlines()
        return sum(1 for _ in takewhile(str.isspace, lines[current_frame.f_lineno - 1]))
    

提交回复
热议问题