Problem with import class

Possible duplicate:
Python import main issue

I have a project with this structure:

project_folder: __init__.py classes_folder: __init__.py class1.py class2.py tests_folder: __init__.py test1.py 

Now I need to import class1.py into test1.py . How can i do this?

+4
source share
3 answers

Assuming PYTHONPATH=. and you are in the project folder , then ...

import classes_folder.class1

By "located" I mean that you are using python from the project folder .

all this is relative to your PYTHONPATH . Keep this in mind.

So, if you are in the project folder/tests_folder to avoid problems, make PYTHONPATH absolute for the root of your project:

export PYTHONPATH=/full/path/to/project_folder

and then you will not have problems when running tests from another folder.

change response to comment about changing python path at runtime

 import sys sys.path.append("/full/path/to/project_folder") 

or even better, you can do this based on where you get python from ...

 import sys,os home_project=os.path.abspath(".") sys.path.append(home_project) 
+2
source
 from ..classes_folder import class1 

Example:

 $ ls -R root root: foobar/ tests/ __init__.py root/foobar: __init__.py mod.py root/tests: __init__.py test1.py $ cat root/foobar/mod.py; echo '###'; cat root/tests/test1.py print "running", __name__ ### from ..foobar import mod $ python -m root.tests.test1 running root.foobar.mod 
+1
source

You can add the following code to classes_folder/__init__.py :

 __all__ = ['class1', 'class2'] 

Then in your test ( test_folder/test1.py ):

 from classes_folder import * 

This way test1.py will reach all your classes within classes_folder

+1
source

Source: https://habr.com/ru/post/1337168/


All Articles