views:

76

answers:

2

I have a project that is structured like this (cut down a lot to give the gist)...

State_Editor/
    bin/
    state_editor/
        __init__.py
        main.py
        features/
            __init__.py
            # .py files
        io/
            __init__.py
            # .py files
        # etc.

You get the idea. Now say for example that foobar.py in features did this... from state_editor.io.fileop import subInPath. Obviously State_Editor needs to be in the path.

I've read about sys.path.append and path configuration files, but I'm not sure how to accomplish what I need to accomplish, or what the most pythonic way to do it is.

The biggest problem is I don't know how to specify "one directory up". Obviously this is .., but I'm not sure how to avoid this being interpreted as a string literal. For example if I do sys.path.append('../') it will literally append ../ to the path.

So my question is, what is the most "pythonic" way to accomplish this?

+3  A: 

In the question as stated, you need 2 leading dots (the module containing the import was state_editor.features.foobar). So:

from ..io.fileop import SubInPath 

Full docs:

http://docs.python.org/reference/simple_stmts.html#the-import-statement

Bill Gribble
also see the examples at [PEP 328](http://www.python.org/dev/peps/pep-0328/)
ma3
+1  A: 

In recent-enough Python versions, "relative imports" as recommended by @fseto may be best (perhaps with a from __future__ import absolute_import at the top of your module). For a solution compatible with a wide range of Python versions, e.g.,

import sys
import os
sys.path.append(os.path.abspath(os.pardir))
Alex Martelli
-1 Modifying sys.path within a library/module is a bad idea, as it could have unforeseen consequences on other modules. See [this discussion](http://stackoverflow.com/questions/1893598/pythonpath-vs-sys-path), for one example.
ma3