Repository: opencv
Issue: Error importing cv2, recursion detected, problem getting PYTHON_EXTENSIONS_PATHS
Labels: category: python bindings,needs investigation,category: 3rdparty

##### System information (version)

- OpenCV == 3.4.10 (built from source)
- Operating System / Platform => Ubuntu 20.04
- Compiler => gcc

##### Detailed description

Hitting "ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation."

While importing cv2, but only while running unit tests in PyCharm, in debug mode. In run mode, everything is fine. If I run the same unit tests from command line, everything is fine also.

I traced the error down to how bootstrap works in `cv2/__init__.py`

I added the following two print statements:

```
   def load_first_config(fnames, required=True):
        for fname in fnames:
            fpath = os.path.join(LOADER_DIR, fname)
            if not os.path.exists(fpath):
                if DEBUG: print('OpenCV loader: config not found, skip: {}'.format(fpath))
                continue
            if DEBUG: print('OpenCV loader: loading config: {}'.format(fpath))
            exec_file_wrapper(fpath, g_vars, l_vars)

            print('in load_first_config:', l_vars['PYTHON_EXTENSIONS_PATHS'])   # < ------ Added

            return True
        if required:
            raise ImportError('OpenCV loader: missing configuration file: {}. Check OpenCV installation.'.format(fnames))

    load_first_config(['config.py'], True)
    load_first_config([
        'config-{}.{}.py'.format(sys.version_info[0], sys.version_info[1]),
        'config-{}.py'.format(sys.version_info[0])
    ], True)

    print('after load_first_config:', l_vars['PYTHON_EXTENSIONS_PATHS'])  # < ------ Added

    if DEBUG: print('OpenCV loader: PYTHON_EXTENSIONS_PATHS={}'.format(str(l_vars['PYTHON_EXTENSIONS_PATHS'])))
    if DEBUG: print('OpenCV loader: BINARIES_PATHS={}'.format(str(l_vars['BINARIES_PATHS'])))
```

running this code

```
sys.OpenCV_LOADER_DEBUG = 1
print('pre-cv2')
import cv2
print('post-cv2')
cv2.setNumThreads(1)
```

in run mode I get this output, and no error:

```
pre-cv2
OpenCV loader: os.name="posix"  platform.system()="Linux"
OpenCV loader: loading config: /home/user-name/project-name/lib/python3.7/site-packages/cv2/config.py
in load_first_config: []
OpenCV loader: loading config: /home/user-name/project-name/lib/python3.7/site-packages/cv2/config-3.7.py
in load_first_config: ['/home/user-name/project-name/lib/python3.7/site-packages/cv2/python-3.7']
after load_first_config: ['/home/user-name/project-name/lib/python3.7/site-packages/cv2/python-3.7']
OpenCV loader: PYTHON_EXTENSIONS_PATHS=['/home/user-name/project-name/lib/python3.7/site-packages/cv2/python-3.7']
OpenCV loader: BINARIES_PATHS=['/home/user-name/project-name/lib']
OpenCV loader: replacing cv2 module
OpenCV loader: DONE
post-cv2
```
 in debug mode:

```
pre-cv2
OpenCV loader: os.name="posix"  platform.system()="Linux"
OpenCV loader: loading config: /home/user-name/project-name/lib/python3.7/site-packages/cv2/config.py
in load_first_config: []
OpenCV loader: loading config: /home/user-name/project-name/lib/python3.7/site-packages/cv2/config-3.7.py
in load_first_config: ['/home/user-name/project-name/lib/python3.7/site-packages/cv2/python-3.7']
after load_first_config: []
OpenCV loader: PYTHON_EXTENSIONS_PATHS=[]
OpenCV loader: BINARIES_PATHS=[]
OpenCV loader: replacing cv2 module
...
ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.
```

You can see that, in debug mode, PYTHON_EXTENSIONS_PATHS is set correctly, inside load_first_config, but is missing outside. In run mode, it is there in both cases.

**conclusion:**

_some how_ the value for key PYTHON_EXTENSIONS_PATHS is getting dropped from `l_vars`, after the call to `load_first_config`. This is a bit baffling to me, I checked `id(l_vars)` inside and outside of `load_first_config`, it's the same object. I don't really understand how this could happen.

##### Issue submission checklist

 - [:heavy_check_mark: ] I report the issue, it's not a question
   <!--
   OpenCV team works with answers.opencv.org, Stack Overflow and other communities
   to discuss problems. Tickets with question without real issue statement will be
   closed.
   -->
 - [:heavy_check_mark:  ] I checked the problem with documentation, FAQ, open issues,
       answers.opencv.org, Stack Overflow, etc and have not found solution
   <!--
   Places to check:
   * OpenCV documentation: https://docs.opencv.org
   * FAQ page: https://github.com/opencv/opencv/wiki/FAQ
   * OpenCV forum: https://answers.opencv.org
   * OpenCV issue tracker: https://github.com/opencv/opencv/issues?q=is%3Aissue
   * Stack Overflow branch: https://stackoverflow.com/questions/tagged/opencv
   -->
 - [ ] I updated to latest OpenCV version and the issue is still there
   <!--
   master branch for OpenCV 4.x and 3.4 branch for OpenCV 3.x releases.
   OpenCV team supports only latest release for each branch.
   The ticket is closed, if the problem is not reproduced with modern version.
   -->
 - [ ] There is reproducer code and related data files: videos, images, onnx, etc
   <!--
   The best reproducer -- test case for OpenCV that we can add to the library.
   Recommendations for media files and binary files:
   * Try to reproduce the issue with images and videos in opencv_extra repository
     to reduce attachment size
   * Use PNG for images, if you report some CV related bug, but not image reader
     issue
   * Attach the image as archite to the ticket, if you report some reader issue.
     Image hosting services compress images and it breaks the repro code.
   * Provide ONNX file for some public model or ONNX file with with random weights,
     if you report ONNX parsing or handling issue. Architecture details diagram
     from netron tool can be very useful too. See https://lutzroeder.github.io/netron/
   -->