python - using __init__.py for modules in multiple dirs
I'm having a hard time understanding this. 开发者_如何学JAVA
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
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! )
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
.
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
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.
精彩评论