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>

<pre><code>&gt;&gt;&gt; import inspect
&gt;&gt;&gt; help(inspect.indentsize)
Help on function indentsize in module inspect:

indentsize(line)
    Return the indent size, in spaces, at the start of a line of text.
</code></pre>

python reflection metaprogramming indentation tokenize