Can a line of Python code know its indentation nesting level?
<p>From something like this:</p>

<pre><code>print(get_indentation_level())

    print(get_indentation_level())

        print(get_indentation_level())
</code></pre>

<p>I would like to get something like this:</p>

<pre><code>1
2
3
</code></pre>

<p>Can the code read itself in this way?</p>

<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>

<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>

<p>Is there a better way to do this which avoids painstaking manual formatting?</p>

<p>Yeah, that's definitely possible, here's a working example:</p>

<pre><code>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()
</code></pre>

python reflection metaprogramming indentation tokenize