S1lentSt0rm
S1lentSt0rm

Reputation: 2039

Import package "x" in module "x": prevent importing itself and import package instead

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

Upvotes: 0

Views: 93

Answers (1)

XrXr
XrXr

Reputation: 2057

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

Upvotes: 1

Related Questions