Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import from sibling directory

I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows:

MainDir ../Dir ..../DirA/ClassA ..../DirB/ClassB 

How would I use sys.path so that ClassB can use ClassA?

like image 580
skylerl Avatar asked Dec 27 '10 22:12

skylerl


1 Answers

as a literal answer to the question 'Python Import from parent directory':

to import 'mymodule' that is in the parent directory of your current module:

import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir)  import mymodule 

edit Unfortunately, the __file__ attribute is not always set. A more secure way to get the parentdir is through the inspect module:

import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) 
like image 125
Remi Avatar answered Oct 02 '22 12:10

Remi