Pythonic module organization - how to access files in root directory?

I have python code in the "project" folder, so my code files are in the / * project. py. I want to have submodules inside it, for example

project/code.py # where code lives
project/mymodule1  # where more code lives
project/mymodule2

each module directory has its own init .py file, for example

project/mymodule1/__init__.py

Suppose I have a test.py file in mymodule1 (project / mymodule1 / test.py), and I would like to refer to something from the "code", for example. import the function "myfunc"

== project/mymodule1/test.py ==
from code import myfunc

the problem is that the "code" will not be found unless the user has placed the "project /" directory in PYTHONPATH. Is there a way to avoid this and use some kind of “relative path” to import myfunc, for example.

from ../code import myfunc

, PYTHONPATH, script. , .

? : PYTHONPATH , , "" - , , , "project/code.py" , , "myfunc".

EDIT: - ? , "mymodule1" :

from .. import foo

"foo" code.py, . init.py mymodule1, :

project/code.py
project/mymodule1/__init__.py
project/mymodule1/module1_code.py

module1_code.py foo, , "code.py".

EDIT: , , , , /sub 1/test, "cd" sub1 "python test.py", . , "", "import project.sub1.test". , , . test.py, /sub 1/. , :

$ cd project/sub1
$ python test.py

:

ValueError: Attempted relative import in non-package

?

.

+5
2

Python 2.5 . . .

:

, - , , distutils setuptools, project, , , from project.code import ... .

, (, , - , sys.path ..), , , PYTHONPATH, sys.path.

, - , , cd'ing project script - , , .

: , :

, :

project/
    __init__.py (empty)
    code.py
    sub1/
        __init__.py (empty)
        test.py

project/code.py:

# code.py (module that resides in main "project" package)

def foo():
    print "this is code.foo"

project/sub1/test.py:

# test.py (module that resides in "sub1" subpackage of main "project" package)

from ..code import foo
foo()

, test.py foo ..code, , code.py ( ..) sub1.test, .

:

shell$ (cd to directory where "project" package is located)
shell$ python
Python 2.6.1 (r261:67515, Aug  2 2010, 20:10:18) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import project.sub1.test
this is code.foo

, from .. import X , .

, from .. import X from project import X, X project, // project/__init__.py.

, from ..code import X from project.code import X.

+3

- src , . myproject __init__.py,

from myproject import code

project
    main.py
    myproject
        __init__.py
        code.py
        module1
        module2

main.py , , , myproject , .

from myproject import myapp
myapp.run()

. , python.

+1

All Articles