KeyError / frozen importlib._bootstrap error on second library import in spyder

Vera picture Vera · Dec 19, 2018 · Viewed 24.8k times · Source

I receive a

File " <frozen importlib._bootstrap_external> ", line 978, in _get_parent_path    
KeyError: 'python_library'

error when I import a library from a subfolder the second time in spyder, but the first time (after restarting spyder) or outside of spyder it works fine.

The code is:

from python_library.tools.test_lib import test_func    
test_func()

where test_lib.py is simply

def test_func():    
    print('Hello!')

And the output is:

runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')
Hello!

runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')    
Reloaded modules: python_library, python_library.tools.test_lib
Traceback (most recent call last):

  File "< ipython-input-2-e750fd08988c >", line 1, in <module>   
    runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')

  File "/home/user/anaconda3/envs/qutip/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 678, in runfile    
    execfile(filename, namespace)

  File "/home/user/anaconda3/envs/qutip/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 106, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/user/Desktop/test.py", line 1, in <module>
    from python_library.tools.test_lib import test_func

  File "<frozen importlib._bootstrap>", line 971, in _find_and_load

  File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked

  File "<frozen importlib._bootstrap>", line 894, in _find_spec

  File "<frozen importlib._bootstrap_external>", line 1157, in find_spec

  File "<frozen importlib._bootstrap_external>", line 1123, in _get_spec

  File "<frozen importlib._bootstrap_external>", line 994, in __iter__

  File "<frozen importlib._bootstrap_external>", line 982, in _recalculate

  File "<frozen importlib._bootstrap_external>", line 978, in _get_parent_path

KeyError: 'python_library'

The error does not occur when the library is not in a subfolder i.e.

from python_library.test_lib2 import test_func

runs arbitrarily often. However I have enough functions that not having subfolders would be very annoying.

This was with spyder-3.3.2, but it also occurred earlier with spyder version 3.3.0-py36_1. The python version is 3.6.4., spyder is installed and updated via anaconda and the 'python_library' was installed via setup.py (setuptools version 40.6.3, also occurred with version 39.2.0-py36_0).

Note: The same error occurred in question How do I solve a KeyError when importing a python module? but that question has no answer, and also no spyder tag.

Answer

Vera picture Vera · Dec 20, 2018

The solution was that there was no empty __init__.py file in the sub-folder tools, only in the super-folder python_library. Adding a file __init__.py into tools made it work.