0

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?

person
  • 205
  • 2
  • 6
  • What is main.py doing? (Given no more info I would put main.py in the root of State_Editor and it would then work as you show) – mmmmmm Sep 27 '10 at 00:27
  • I figured state_editor was supposed to hold the scripts (following a packaging guide I read in The Python Tutorial) I read earlier. – person Sep 27 '10 at 00:32
  • That'll definitely work though, and now that I'm looking around that seems pretty common. Thanks. – person Sep 27 '10 at 00:46

2 Answers2

3

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
  • 1,797
  • 12
  • 15
1

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
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    -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. – snapshoe Sep 27 '10 at 02:37