Fab von Bellingshausen Fab von Bellingshausen - 3 months ago 7
Python Question

Can a line of Python code know its indentation level?

From something like this:

print(get_indentation_level())

print(get_indentation_level())

print(get_indentation_level())


I would like to get something like this:

1
2
3


Can the code read itself in this way?

BPL BPL
Answer

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()