Search code examples
pythonimporterror

Accessing variable, stored in package's init from file in package


I have a package named pkg and array named arr in __init__ file of this package. Also, I have file file.py in this package where I write from pkg import arr but it throws ImportError. How to import array properly?

Tree would look like this

pkg
- file.py
- __init__.py

__init__.py

arr = ['a', 'b', 'c']

file.py

from pkg import arr # ImportError raises here

print (arr)

Solution

  • __init__.py defines how your package looks from outside.

    Try importing like this from . import arr, this basically means from current module import arr.

    When asking about an error you should also provide the error message, ImportError is not enough. It could be a circular-import related error or a missing-library kind of error. The message usually helps a lot.