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

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

    To solve the ”real” problem that lead to your question you could implement a contextmanager which keeps track of the indention level and make the with block structure in the code correspond to the indentation levels of the output. This way the code indentation still reflects the output indentation without coupling both too much. It is still possible to refactor the code into different functions and have other indentations based on code structure not messing with the output indentation.

    #!/usr/bin/env python
    # coding: utf8
    from __future__ import absolute_import, division, print_function
    
    
    class IndentedPrinter(object):
    
        def __init__(self, level=0, indent_with='  '):
            self.level = level
            self.indent_with = indent_with
    
        def __enter__(self):
            self.level += 1
            return self
    
        def __exit__(self, *_args):
            self.level -= 1
    
        def print(self, arg='', *args, **kwargs):
            print(self.indent_with * self.level + str(arg), *args, **kwargs)
    
    
    def main():
        indented = IndentedPrinter()
        indented.print(indented.level)
        with indented:
            indented.print(indented.level)
            with indented:
                indented.print('Hallo', indented.level)
                with indented:
                    indented.print(indented.level)
                indented.print('and back one level', indented.level)
    
    
    if __name__ == '__main__':
        main()
    

    Output:

    0
      1
        Hallo 2
          3
        and back one level 2
    

提交回复
热议问题