brad
brad

Reputation: 61

python - using __init__.py for modules in multiple dirs

I'm having a hard time understanding this.

Lets assume I have a directory tree that looks like this:

~/speech
-- __init__.py
-- program.py
----------------
~/speech/parts
----__init__.py
----noun.py
----verb.py
----------------
~/speech/sentence
----__init__.py
----subject.py
----predicate.py

the __init__.py files are blank. I created them by issuing $ touch __init__.py
when i try to import anything, I get NameError: 'whatever' not defined. I've tried the whatever as both the directory name, and the individual file names.

every other problem i've had in python has been because I'm over-thinking things and trying to make it more complicated than it really is. ( curse the c++ habits! )

Upvotes: 1

Views: 1879

Answers (3)

brad
brad

Reputation: 61

Ok, i finally figured it out.

If I want it to look like "java-style classes", then I import via:

import parts.noun  
import sentence.subject  
parts.noun.defineNouns()  
sentence.subject.thePersonOrThing()  

If I want it to look more like C/++ style lib call, then I import via:

from parts.noun import defineNouns  
from sentence.subject import thePersonOrThing  
defineNouns()  
thePersonOrThing()  

*sigh* it's so simple, it's hard.

Upvotes: 1

Rafael Ferreira
Rafael Ferreira

Reputation: 1288

you can quickly add your current directory to the python search path with:

export PYTHONPATH=$(pwd)

Here's some background information you should read:

Python's Module Search Path

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Unless ~ is your current directory or is in sys.path (which it shouldn't be) you won't be able to use any packages contained in it, including speech and its subpackages. Put the directory structure somewhere sane and add that path to $PYTHONPATH.

Upvotes: 1

Related Questions