Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules from parent folder

I am running Python 2.5.

This is my folder tree:

ptdraft/   nib.py   simulations/     life/       life.py 

(I also have __init__.py in each folder, omitted here for readability)

How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.

Note: The main module being run is in the ptdraft folder.

like image 587
Ram Rachum Avatar asked Apr 03 '09 14:04

Ram Rachum


People also ask

How do I import a parent directory in Python?

In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.

How do I import package modules?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.

Should I use relative or absolute imports Python?

With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.


2 Answers

You could use relative imports (python >= 2.5):

from ... import nib 

(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports

EDIT: added another dot '.' to go up two packages

like image 181
f3lix Avatar answered Sep 20 '22 18:09

f3lix


Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

import os import sys import inspect  currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir)   import mymodule 

edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file

like image 39
Remi Avatar answered Sep 21 '22 18:09

Remi