1

I was trying to understand how packages like Numpy/Pandas makes its imports, and Numpy seems to call from its core package. For example, in numpy/linalg/linalg.py, it makes an import

from numpy.core import (
    array, asarray, zeros, empty, empty_like, intc, single, double,
    csingle, cdouble, inexact, complexfloating, newaxis, all, Inf, dot,
    add, multiply, sqrt, fastCopyAndTranspose, sum, isfinite,
    finfo, errstate, geterrobj, moveaxis, amin, amax, product, abs,
    atleast_2d, intp, asanyarray, object_, matmul,
    swapaxes, divide, count_nonzero, isnan, sign
)

in order to make its basic operations. However, the folder structure is

numpy
   > core
       > __init__.py
       > _asarray.py
       > _dtype.py
       ... 
   > linalg
       > __init__.py
       > linalg.py      <--- Looking at this one
       ...
   > fft 
       > __init__.py
       > helper.py
       > _pocketfft.py  <--- Same thing happens here
       ...

But since core is a sister directory to linalg, how is it that numpy/linalg/linalg.py is able to use from numpy.core import ... since it wouldn't be able to capture anything from a parent directory?

My problem is that I have a folder structure:

pkg
   > banana
       > __init__.py
       > banana.py
   > fruit
       > __init__.py
       > fruit.py

where

# pkg/fruit/__init__.py
from .fruit import func1
# pkg/banana/__init__.py
from .banana import *
from ..fruit import func1 # This won't work

and I'd like to have func1 be used in the banana package

Nicolas Shu
  • 327
  • 2
  • 8

3 Answers3

2

from numpy.core import ... is an absolute import. The import mechanism looks for numpy in one of the directories listed in sys.path, not the directory where the current file is stored.

I suspect your problem is that pkg.__init__.py doesn't exist, meaning pkg is simply a directory, not a Python package.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

The problem might be how you are running it. I've solved similar problems by going to the directory above pkg and running python -m pkg.banana.__init__.

Here's question that has a lot of good information. Python Relative Imports

RedKnite
  • 1,525
  • 13
  • 26
0

Use an absolute import: from pkg.fruit import func1. As @chepner points out, this is what the import in numpy is doing.

If you are using python 2 then pkg/__init__.py must exist, but this requirement no longer exists in python 3.

alani
  • 12,573
  • 2
  • 13
  • 23