Skip to content
Advertisement

Import python package from local directory into interpreter

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement