tags:

views:

1391

answers:

4

I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in "sys.path.insert(0,'.')". Is there a better way?

Also, "from . import mypackage" fails with this error: "ValueError: Attempted relative import in non-package"

A: 

not bad, But sys.path should include current directory already.
Edit: import . (or from . import sth) maybe not a good practice, why not just import mypackage

sunqiang
+3  A: 

See the documentation for sys.path:

http://docs.python.org/library/sys.html#sys.path

To quote:

If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.

So, there's no need to monkey with sys.path if you're starting the python interpreter from the directory containing your module.

Also, to import your package, just do:

import mypackage

Since the directory containing the package is already in sys.path, it should work fine.

SpoonMeiser
A: 

You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import (which means "import from the same package I got imported from") doesn't work. import mypackage will be fine once you ensure the parent directory of mypackage is in sys.path (how you managed to get your current directory away from sys.path I don't know -- do you have something strange in site.py, or...?)

To get your current directory back into sys.path there is in fact no better way than putting it there;-).

Alex Martelli
Python 2.5 for Ubuntu 8.10 does not have the current directory (empty string) in sys.path for the interpreter. I didn't change anything, so it somehow got shipped that way. I just installed 3.0 and sys.path DOES have '' in sys.path.
projectshave
@projectshave, OK, Ubuntu's no doubt got their reasons! I haven't noticed that in 8.04 (what we currently use at work) but maybe I just wasn't paying enough attention.
Alex Martelli
I am partially wrong. Python invoked from a shell has the current directory in sys.path. Python invoked from Emacs does not have the current directory. Strange.
projectshave
Ah well, then it's Emacs who's got their reasons as opposed to Ubuntu's (as a vim user I don't really know;-). You can conditionally insert '.' in your sys.path iff not there of course.
Alex Martelli
A: 

A simple way to make it work is to run your script from the parent directory using python's -m flag, e.g. python -m packagename.scriptname. Obviously in this situation you need an __init__.py file to turn your directory into a package.

bradley.ayers