0

I run into problems when using a project structure as suggested here: What is the best project structure for a Python application?.

Imagine a project layout like this:

Project/
|-- bin/
|   |-- project.py
|
|-- project/
|   |-- __init__.py
|   |-- foo.py

In bin/project.py I want to import from package project.

#project.py
from project import foo

Since sys.path[0] is always Project/bin when running bin/project.py, it tries to import the module bin/project.py (itself) resulting in an attribute error. Is there a way to use this project layout without playing around with sys.path in the module bin/project.py? I basically would need a "importpackage" statement, that ignores modules with same name.

Since the project structure is suggested, I'm wondering why no one else has this kind of problems...

Community
  • 1
  • 1
S1lentSt0rm
  • 1,989
  • 2
  • 17
  • 28

1 Answers1

1

You could try:

import imp
module_name = imp.load_source('project','../project')

module_name would be the package.

EDIT:

For python 3.3+

import importlib.machinery

loader = importlib.machinery.SourceFileLoader("project", "../project")
foo = loader.load_module("project")

Source

Community
  • 1
  • 1
XrXr
  • 2,027
  • 1
  • 14
  • 20
  • I'm actually using python 3.3, the module imp in python 3.3 has no method load_source – S1lentSt0rm Feb 06 '14 at 10:37
  • Added 3.3+ equivalent. – XrXr Feb 06 '14 at 15:44
  • Thanks for your reply. I hoped there is some "importpackage" statement, that explicitly only loads packages and skips single file modules to avoid importing itself. The way you do it might be a solution (even if I get some weird OS permission errors), but I wanted to avoid the use of relative paths. I see not much benefit in using the example above instead of "sys.path.append(sys.path.pop(0))". – S1lentSt0rm Feb 06 '14 at 16:52