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?
from . import mypackage
fails with this error:
ValueError: Attempted relative import in non-package
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;-).
See the documentation for sys.path:
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 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:
Since the directory containing the package is already in sys.path, it should work fine.