一行Python代码可以知道其缩进嵌套级别吗? [英] Can a line of Python code know its indentation nesting level?

查看:225
本文介绍了一行Python代码可以知道其缩进嵌套级别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从类似这样的东西:

print(get_indentation_level())

    print(get_indentation_level())

        print(get_indentation_level())

我想得到这样的东西:

1
2
3

代码可以这样读取自身吗?

Can the code read itself in this way?

我想要的是更多嵌套代码部分的输出.以相同的方式使代码更易于阅读,也将使输出更易于阅读.

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.

当然我可以使用例如.format(),但是我想到的是一个自定义打印功能,该功能将print(i*' ' + string)其中i是缩进级别.这将是在我的终端上使输出可读的一种快速方法.

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

是否有更好的方法来避免繁琐的手动格式化?

Is there a better way to do this which avoids painstaking manual formatting?

推荐答案

如果您要缩进而不是空格和制表符,则是嵌套级别,那么事情就会变得棘手.例如,在以下代码中:

If you want indentation in terms of nesting level rather than spaces and tabs, things get tricky. For example, in the following code:

if True:
    print(
get_nesting_level())

get_nesting_level的调用实际上嵌套了一层深度,尽管get_nesting_level调用的行上没有前导空格.同时,在以下代码中:

the call to get_nesting_level is actually nested one level deep, despite the fact that there is no leading whitespace on the line of the get_nesting_level call. Meanwhile, in the following code:

print(1,
      2,
      get_nesting_level())

get_nesting_level的调用嵌套在零级深度处,尽管其行中存在前导空白.

the call to get_nesting_level is nested zero levels deep, despite the presence of leading whitespace on its line.

在以下代码中:

if True:
  if True:
    print(get_nesting_level())

if True:
    print(get_nesting_level())

对两个get_nesting_level的调用处于不同的嵌套级别,尽管前导空白是相同的.

the two calls to get_nesting_level are at different nesting levels, despite the fact that the leading whitespace is identical.

在以下代码中:

if True: print(get_nesting_level())

那是嵌套的零级,还是一级?就形式语法中的INDENTDEDENT标记而言,它的深度为零,但是您可能会有不同的感觉.

is that nested zero levels, or one? In terms of INDENT and DEDENT tokens in the formal grammar, it's zero levels deep, but you might not feel the same way.

如果要执行此操作,则必须在整个调用之前将整个文件标记化,并计数INDENTDEDENT标记. tokenize 模块对于此类功能非常有用:

If you want to do this, you're going to have to tokenize the whole file up to the point of the call and count INDENT and DEDENT tokens. The tokenize module would be very useful for such a function:

import inspect
import tokenize

def get_nesting_level():
    caller_frame = inspect.currentframe().f_back
    filename, caller_lineno, _, _, _ = inspect.getframeinfo(caller_frame)
    with open(filename) as f:
        indentation_level = 0
        for token_record in tokenize.generate_tokens(f.readline):
            token_type, _, (token_lineno, _), _, _ = token_record
            if token_lineno > caller_lineno:
                break
            elif token_type == tokenize.INDENT:
                indentation_level += 1
            elif token_type == tokenize.DEDENT:
                indentation_level -= 1
        return indentation_level

这篇关于一行Python代码可以知道其缩进嵌套级别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆