1

I get an ImportError when I am importing from a sub-module in the way I thought One Was Supposed To Do It.

I have the following package:

pkg/
  __init__.py
  cow.py
  pizza.py
  pkg.py
  components/
    components.py
    otherstuff.py
    __init__.py

cow.py:

print "Hello"
from components import foodle

components.py:

foodle=5

and the __init__'s are empty.

I am having trouble putting things in the right place or organizing them properly. When, from the pkg directory, I try

from pkg import foodle

I get "ImportError: cannot import name foodle"

What is the right way to arrange files and import from submodules? I have read How to import python file from git submodule ; I have tried messing with sys.path in components/__init__.py and in cow.py, to no avail. This package is shared on git, so it needs to be portable. components is actually a git sub-module.

Putting from components import * in the __init__py in components/ seems to work, but I thought usually that file stays empty.

Community
  • 1
  • 1
CPBL
  • 3,783
  • 4
  • 34
  • 44

1 Answers1

1

The elements I was missing are (these are my interpretation, may still be incorrect):

  • If it's a package (with __init__.py), use it from outside the pkg folder, not from inside. ie, using a package both ways (calling from outside and using modules from within) might be hard to set up, so don't. This is the main insight that solves my problem.

  • the dot notation for getting submodules and subpackages works both for files and for folders within pkg. Thus, from some other folder, but with pkg in my path, I can call any of the following:

    import pkg
    from pkg.cow import foodle
    from pkg.components import foodle
    from pkg.components.components import foodle
    
nwinkler
  • 52,665
  • 21
  • 154
  • 168
CPBL
  • 3,783
  • 4
  • 34
  • 44