'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 1:[1]
__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.
Solution 2:[2]
If you want to access the list arr in this manner. The file file.py should be in the base directory not in the package.
Hence the tree should be:
base
- pkg
- __init__.py
- file.py
Or, if you want to access the list from inside the package the import statement should be as the following:
from __init__ import arr
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | P I N C O |
| Solution 2 | JEFFRIN JACOB |
