Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Importing a file from a parent folder

Tags:

python

...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo.

I have a python file that wishes to import a file (that is in its parent directory). Can you help me figure out how my child file can successfully import its a file in its parent directory. I am using python 2.7.

The structure is like so (each directory also has the __init__.py file in it):

StockTracker/  
└─ Comp/  
   ├─ a.py  
   └─ SubComp/  
      └─ b.py

Inside b.py, I would like to import a.py: So I have tried each of the following but I still get an error inside b.py saying "There is no such module a".

import a

import .a

import Comp.a

import StockTracker.Comp.a

import os
import sys
sys.path.append('.')
import a    
sys.path.remove('.')
like image 918
Sascha Avatar asked Jan 09 '11 00:01

Sascha


2 Answers

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo.

Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from .. import formats
from ..filters import equalizer

Quote from here http://docs.python.org/tutorial/modules.html#intra-package-references

like image 67
DixonD Avatar answered Sep 23 '22 17:09

DixonD


from .. import a

Should do it. This will only work on recent versions of Python--from 2.6, I believe [Edit: since 2.5].

Each level (Comp and Subcomp) must also be have an __init__.py file for this to work. You've said that they do.

like image 20
Thomas K Avatar answered Sep 21 '22 17:09

Thomas K