user3871
user3871

Reputation: 12716

Import error with unit tests: "No module named ..." from local libary

I'm new to Python (JS developer) and am trying to run a testing suite. My project folder structure is as such:

project/
  __init__.py
  libs/
    __init__.py
    s3panda.py 
  tests
    __init__.py
    tests_s3panda.py

In terminal, I'm running python tests_s3panda.py.

I don't understand how it's unable to find a local module:

Traceback (most recent call last): File "tests_s3panda.py", line 7, in from libs.s3panda import S3Panda ImportError: No module named libs.s3panda

tests_s3panda.py snippet:

from __future__ import absolute_import

import unittest

import pandas as pd

from libs.s3panda import S3Panda


class TestS3Panda(unittest.TestCase):
    ...

Doing from ..libs.s3panda import S3Panda for relative path, I get:

ValueError: Attempted relative import in non-package

Upvotes: 2

Views: 5000

Answers (1)

Justin Payan
Justin Payan

Reputation: 11

I believe the fact that there is no init.py in the top-level folder means that Python is not aware that libs and tests are both part of the same module called project.

Try adding an __init__.py to your project folder, then write the import statement as from project.libs.s3panda import S3Panda. In general, you want to specify absolute imports rather than relative imports (When to use absolute imports).

Upvotes: 1

Related Questions