importing a module from a specific directory

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 23 02:21:44 EDT 2007


En Sun, 22 Jul 2007 09:03:43 -0300, O.R.Senthil Kumaran  
<orsenthil at users.sourceforge.net> escribió:

>>  I would like to organize them into directory structure in
>>  which there is a 'main' directory, and under it directories for
>>  specific sub-tasks, or sub-experiments, I'm running (let's call them
>>  'A', 'B', 'C').
>>  Is there a neat clean way of achieving the code organization?
>>
>
> This is a kind of a frequently asked question at c.l.p and every  
> programmer I
> guess has to go through this problem.
> If you look around c.l.p you will find that one of the good ways to  
> solve this
> problem with the python interpretor <2.5 is:
>
>>>> import sys
>>>> sys.path.append(os.path.abspath(os.pardir))

I would write it as  
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  
- or certainly split it into two lines, because the current directory may  
not be the directory containing the script.

> But, if you are using Python 2.5, you are saved.
>
> <snip>
> 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:

Note that this only applies to *packages*, not alone modules. And if you  
already have a package, it's better to put the driver/test/demo code out  
of the package itself, this way it must import the package the same way as  
any other client code. I usually place them in the directory containing  
the package (so "import package" just works). Other people prefer a  
different layout; search for some recent posts on this subject.

-- 
Gabriel Genellina




More information about the Python-list mailing list