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?

3
  • 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) Commented Sep 27, 2010 at 0:27
  • I figured state_editor was supposed to hold the scripts (following a packaging guide I read in The Python Tutorial) I read earlier. Commented Sep 27, 2010 at 0:32
  • That'll definitely work though, and now that I'm looking around that seems pretty common. Thanks. Commented Sep 27, 2010 at 0:46

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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))

1 Comment

-1 Modifying sys.path within a library/module is a bad idea, as it could have unforeseen consequences on other modules. See this discussion, for one example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.