Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a class from a folder at another level

Tags:

python

import

I have a python application like this

/
/crawl.py
/crawl/__init__.py
/crawl/john.py
/tests/test_john.py

What I am trying to do, is run the unit test test_john.py which needs to use john.py but it's in another folder.

In my tests/test_john.py I get this when I run it

Traceback (most recent call last):
  File "test_john.py", line 2, in <module>
    from john import John
ImportError: No module named john

So how can I import a class, from the crawl folder....

like image 711
Wizzard Avatar asked Oct 30 '11 08:10

Wizzard


People also ask

Can you import a folder in Python?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory. As sys.

Can we import class in Python?

It allows us to use functions and classes kept in some other file inside our current code. Python provides us with various ways in which we can import classes and functions using the import statements.

How do I import a module from the root directory?

In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.


2 Answers

If your root folder is in your pythonpath and you make it an importable package as follows:

/__init__.py
/crawl.py
/crawl/__init__.py
/crawl/john.py
/tests/__init__.py
/tests/test_john.py

you can do:

from crawl.john import John

or

from ..crawl.john import John
like image 168
joaquin Avatar answered Sep 29 '22 09:09

joaquin


If your OS supports it, put a symbolic link to ../crawl in the test directory and then use from crawl.john import John.

like image 44
ekhumoro Avatar answered Sep 29 '22 11:09

ekhumoro