views:

222

answers:

2

Python can only import files from the current working directory, or from its path, I guess, but this means that if I'm working in a subdirectory on a certain project, I can't import stuff from a parent directory that I wrote to simplify things or provide shortcuts.

This is more for interactive work in IPython and the like, not developing code to be distributed to others. I guess another option is IPython's %run command, which would allow for importing stuff from parent directories, but it also runs anything not in a function, and the functions end up in the root namespace, which might be bad sometimes.

More generally, I guess I'm asking how your Python development folder(s) are organized.

+3  A: 

You can use

import sys
sys.path.append(<directory path>)

from module import features

Which is what I do, and it works for me.

This appends directory path to the path which python searches when loading modules (files with convenience functions).

For example, if your convenience functions are in directory C:\dev\python\conv, and you had a file named stuff.py in that directory which contained a helper function called myFunction, you would use the following commands to access and run this function.

import sys
sys.path.append("C:\\dev\\python\\conv")

from stuff import myFunction
myFunction()

If you don't want everything in stuff to be in the global namespace do this:

import sys
sys.path.append("C:\\dev\\python\\conv")
import stuff
stuff.myFunction()
ecounysis
Is this permanent, or do you have to append it every session?
endolith
Unless you add it to the PYTHONPATH environment variable you'll have to append it to sys.path every session.http://docs.python.org/using/cmdline.html#envvar-PYTHONPATHhttp://docs.python.org/tutorial/modules.html#the-module-search-path
ecounysis
+4  A: 
Alex Martelli
That's pretty weird. Why don't they just use normal filenames at that point instead of inventing a new syntax?
endolith
"Normal filenames" for relative syntax, e.g. on Windows, would be something like `'..\\..\\..\\foo'` -- and of course that wouldn't work on Unix (requiring `'../../../foo'` instead). Even assuming one standardizes on the latter, that's 9 leading punctuation characters (12 on Windows) instead of three -- and many of those visually very obtrusive -- plus the quotes (you try to design a lexer that can gobble up this "normal filename" garbage w/o them;-). There's an abundance of languages that successfully strive to look like line noise by abundance of punctuation: Python's not one of them.
Alex Martelli