VSCode Python region doesn't work in all cases

Viewed 40

I'm using VSCode to write Python code. I'd like to use #region foo and #endregion foo to provide custom folding. This sometimes works. When I say sometimes I mean it works for some instances but not others.

import pytest
from unittest.mock import Mock

def test_advanced_function_call_count(myfile, monkeypatch, mocker):
    # region setup
    monkeypatch.setattr(myfile, 'basic_function', Mock())
    # endregion setup
    
    # region execution
    myfile.advanced_function2()
    assert myfile.basic_function.call_count == 1
    # endregion execution

In the above example I can fold # region setup but I can't fold # region execution. In my real code there doesn't appear to be a pattern of it only folding one region, the first region, or the last region. It appears to be random.

Any ideas what is preventing random regions from being able to fold?

1 Answers

According to this page in github.

This should be caused by overlapping folding areas (def itself has a hidden fold). Take your code as an example:

def test_advanced_function_call_count(myfile, monkeypatch, mocker):  #region A start
    # region setup                                                   #region B start
    monkeypatch.setattr(myfile, 'basic_function', Mock())
    # endregion setup                                                #region B end
    
    # region execution                                               #region C start
    myfile.advanced_function2()
    assert myfile.basic_function.call_count == 1                     #region A end
    # endregion execution                                            #region C end

The inclusion relationship between region A and region B can be allowed:

# Range A start
  # Range B start
  # Range B end
# Range A end

Something I found out is if the # endregion is after the last line of code in a def then it's not valid.

However, there is a staggered inclusion relationship between A and C, which leads to the failure of C folding:

# Range A start
  # Range C start
# Range A end
  # Range C end
Related