Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import python package from local directory into interpreter

Tags:

python

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 
like image 235
projectshave Avatar asked Jul 11 '09 00:07

projectshave


People also ask

Can import Python file from same directory?

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.

Can I import a package in a function Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

How do I call a package in Python?

First, we create a directory and give it a package name, preferably related to its operation. Then we put the classes and the required functions in it. Finally we create an __init__.py file inside the directory, to let Python know that the directory is a package.


2 Answers

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.

like image 97
Alex Martelli Avatar answered Sep 17 '22 12:09

Alex Martelli


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.

like image 42
SpoonMeiser Avatar answered Sep 21 '22 12:09

SpoonMeiser