1

Currently, I'm playing around with absolute and relative imports for my tests. Below is the example of the file structure.

File Structure:

project/
        main_script.py
        input1.csv
        input2.csv
        
        Testing/
                test_script.py
                test_input1.csv
                test_input2.csv
                test_output.csv

Code in main_script.py

def function1():
    {function definition here}

def function2():
    {function definition here}

def function3():
    {function definition here}

Code in test_script.py

import pytest 
from ..main_script import function1, function2, function3

The output I get when running test_script:

ImportError: attempted relative import with no known parent package

From the examples I've read from different sources and tutorials I have watched, this should have been the solution to my problem but it's coming out with more errors. Why is that?

MikeO56
  • 15
  • 5

1 Answers1

1

You can try any one of these ways -

  1. Use absolute import
  2. Use standard way of import and remove from keyword Example: import main_script.function1
  3. Put this inside your package's init.py - For relative imports to work in Python 3.6 - import os, sys; sys.path.append(os.path.dirname(os.path.realpath(file))) And now use normal import statement like : from main_script import function1

Reference Attached

Do let me know if this helps out. Happy Learning!!

  • The last method worked! A follow-up question to this is why can't my test script read *.csv files which is currently in the same folder as the test script. A FileNotFoundError would pop out. Is there any way to solve this? Thank you again for the solution above!! – MikeO56 Feb 23 '22 at 04:05
  • Refer this post and let me know if it helps in solving the issue(https://stackoverflow.com/questions/21957131/python-not-finding-file-in-the-same-directory) OR You can use absolute path like **Users/Documents/employee1.csv** - – Nishi Agarwal Feb 27 '22 at 06:46
  • Using absolute path works but I would rather not let users manually change the code so instead, I went with this solution ([Link](https://stackoverflow.com/questions/35384358/how-to-open-my-files-in-data-folder-with-pandas-using-relative-path)). Thanks again for your help! – MikeO56 Feb 28 '22 at 02:45