[Python-au] import stuff from parent directory

Nick Coghlan ncoghlan at iinet.net.au
Fri Dec 23 06:48:22 CET 2005


Mike Dewhirst wrote:
> I tried understanding packages and search paths but they don't quite fit 
>  with what I'm trying to do. Also, packages are a bit advanced for me 
> just yet.
> 
> I already put my working directory into the path and that works fine. I 
> can run 'c:\working_dir\python prog.py' successfully. That working dir 
> contains refactored stuff which I want to import into new software 
> written in subdirectories of that wd.
> 
> I don't think I should be forever adding subdirectories to the path.
> 
> How do I 'import ../prog'?
> 
> Should it happen that way?
> 
> Should I swallow hard and get into packages?

Packages aren't that hard. Just put an empty "__init__.py" in working_dir and
each of the subdirectories.

Then "import prog" from within the subdirectories will try the subdirectory
first, and when that fails, will try the parent directory. Only if both of
those fail will it try the main sys.path, so you need to be careful not to
shadow standard library modules that you want to use.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org



More information about the python-au mailing list