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

前端 未结 5 629
失恋的感觉
失恋的感觉 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:11

    Yeah, that's definitely possible, here's a working example:

    import inspect
    
    def get_indentation_level():
        callerframerecord = inspect.stack()[1]
        frame = callerframerecord[0]
        info = inspect.getframeinfo(frame)
        cc = info.code_context[0]
        return len(cc) - len(cc.lstrip())
    
    if 1:
        print get_indentation_level()
        if 1:
            print get_indentation_level()
            if 1:
                print get_indentation_level()
    

提交回复
热议问题